Learn Python

S3CloudHub - Nov 29 '21 - - Dev Community

Python

Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.

It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library.

It was created by Guido van Rossum, and released in 1991.

It is used for:
web development (server-side),
software development,
mathematics,
system scripting.

Image description

What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.

Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.

Image description

Python Installation:

Many PCs and Macs will have python already installed.

Image description

To check if you have python installed on a Windows PC, search in the start bar for Python or run the following on the Command Line
(cmd.exe):
C:\Users\Your Name>python --version

To check if you have python installed on a Linux or Mac, then on linux open the command line or on Mac open the Terminal and type:
python --version

Python Syntax and Comments:

Image description

Python syntax can be executed by writing directly in the Command Line:
>>> print("Hello, World!")
Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:
C:\Users\Your Name>python myfile.py
Python Indentation:
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example:

if 5 > 2:
  print("Five is greater than two!")
Enter fullscreen mode Exit fullscreen mode

Single-Line Comments:

Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

Comments start with a #, and Python will ignore them:
Example

#This is a comment
print("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

**Multi-Line Comments:
**Example

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Enter fullscreen mode Exit fullscreen mode

Python Variable and Data Types:

Variables are containers for storing data values.

Image description

Creating Variables:
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

Example

x = 5
y = "John"
print(x)
print(y)
Enter fullscreen mode Exit fullscreen mode

Get the Type:
You can get the data type of a variable with the type() function.
Example

x = 5
y = "John"
print(type(x))
print(type(y))
Enter fullscreen mode Exit fullscreen mode

**Case-Sensitive:
**Variable names are case-sensitive.
Example

This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
Enter fullscreen mode Exit fullscreen mode

Built-in Data Types:
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

Python Conditions and If statements:

Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b

Image description

These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:
  print("b is greater than a")
Enter fullscreen mode Exit fullscreen mode

Indentation:
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

Elif:
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".

Example

a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
Enter fullscreen mode Exit fullscreen mode

Getting the Data Type:
You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:

x = 5
print(type(x))
Enter fullscreen mode Exit fullscreen mode

Python Loops:

Python has two primitive loop commands:
while loops
for loops

The while Loop:

Image description

With the while loop we can execute a set of statements as long as a condition is true.
Example

Print i as long as i is less than 6:
i = 1
while i < 6:
  print(i)
  i += 1
Enter fullscreen mode Exit fullscreen mode

Python For Loops:

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Image description

Example

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
Enter fullscreen mode Exit fullscreen mode

Looping Through a String:
Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":

for x in "banana":
  print(x)
Enter fullscreen mode Exit fullscreen mode

Break, Continue, and Pass:

Image description

Break Statement:
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break
Enter fullscreen mode Exit fullscreen mode

Continue Statement:
With the continue statement we can stop the current iteration of the loop, and continue with the next:

Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
Enter fullscreen mode Exit fullscreen mode

Pass Statement:
for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.

Example

for x in [0, 1, 2]:
  pass
Enter fullscreen mode Exit fullscreen mode

Python For Else:

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

Image description

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
  print(x)
else:
  print("Finally finished!")
Enter fullscreen mode Exit fullscreen mode

Python Functions:

A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.

Image description

Creating a Function:
In Python a function is defined using the def keyword:

Example

def my_function():
  print("Hello from a function")
Enter fullscreen mode Exit fullscreen mode

Calling a Function:
To call a function, use the function name followed by parenthesis:
Example

def my_function():
  print("Hello from a function")
my_function()
Enter fullscreen mode Exit fullscreen mode

Arguments:
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Enter fullscreen mode Exit fullscreen mode

Number of Arguments:
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes")
Enter fullscreen mode Exit fullscreen mode

Default Parameter Value:
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:

Example

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Enter fullscreen mode Exit fullscreen mode

Python Lambda:

A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.

Image description

Syntax:
lambda arguments : expression

The expression is executed and the result is returned:

Example
Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))
Enter fullscreen mode Exit fullscreen mode

Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the number you send in:

Example

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))
Enter fullscreen mode Exit fullscreen mode

Python Arrays:

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

Image description

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.

Access the Elements of an Array:
You refer to an array element by referring to the index number.

Example
Get the value of the first array item:

x = cars[0]
Enter fullscreen mode Exit fullscreen mode

Adding Array Elements:
You can use the append() method to add an element to an array.

Example
Add one more element to the cars array:

cars.append("Honda")
Enter fullscreen mode Exit fullscreen mode

Removing Array Elements:
You can use the pop() method to remove an element from the array.

Example
Delete the second element of the cars array:

cars.pop(1)
Enter fullscreen mode Exit fullscreen mode

You can also use the remove() method to remove an element from the array.
Example
Delete the element that has the value "Volvo":
cars.remove("Volvo")

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .