20
Learn 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.
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.
Many PCs and Macs will have python already installed.
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 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!")
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!")
**Multi-Line Comments:
**Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Variables are containers for storing data values.
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)
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))
**Case-Sensitive:
**Variable names are case-sensitive.
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
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 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
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")
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")
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))
Python has two primitive loop commands:
while loops
for loops
The while Loop:
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
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.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
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)
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
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)
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
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
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!")
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.
Creating a Function:
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
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()
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")
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")
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")
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
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))
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))
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
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]
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")
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)
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")
20