Python PDF
Python PDF
These conditions can be used in several ways, most commonly in "if statements"
and loops.
a = 33 b is greater than a
b = 200
if b > a:
print("b is greater than a")
Elif
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".
a = 33 a and b are equal
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The els keyword catches anything which isn't caught by the preceding
e
conditions.
a = 200 a is greater than b
b = 33 if b
> a:
print("b is greater than a") elif a
== b:
print("a and b are equal")
else: print("a is greater than
b")
In this example is greater to b, so the first condition is not true, also
a
the eli condition is not true, so we go to the else condition and print to
screen
f that "a is greater than b".
Short Hand If
If you have only one statement to execute, you can put it on the same line as
the if statement.
a = 200 "a is greater than b"
b = 33
Example
One line if else statement, with 3 conditions:
a = 330 =
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
The and keyword is a logical operator, and is used to combine conditional
statements:
a = 200 b = 33 c Both conditions are True
= 500 if a > b
and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional
statements:
a = 200 b = 33 At least one of the conditions is
c = 500 if a > b True
or a > c:
print("At least one of the conditions is True")
Example
Print a message once the condition is false:
i=1 1
while i < 6: 2
print(i) 3
i += 1 4
else: 5
print("i is no longer less than
6") i is no longer less than 6
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 language, 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.
Print each fruit in a fruit list:
fruits = ["apple", "banana", apple
"cherry"] for x in fruits: print(x) banana
cherry
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6): 0
print(x) else: 1
print("Finally finished!") 2
3
4
5
Finally finished!
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Python Functions
A function is a block of code which only runs when it is called.
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:
def my_function(): Hello from a function
print("Hello from a function")
my_function()
Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
def my_function(fname): Emil Refsnes
print(fname + " Refsnes") Tobias Refsnes
Linus Refsnes
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Return Values
To let a function return a value, use the return statement:
def my_function(x): 15
return 5 * x 25
45
print(my_function(3))
print(my_function(5))
print(my_function(9))
Recursion
Python also accepts function recursion, which means a defined function can call
itself.
To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.
Recursion Example
def tri_recursion(k): Recursion Example Results
if(k>0): 1
result = k+tri_recursion(k-1) 3
6
print(result)
else: result
10
=0 15
return result 21
Example
Create an array containing car names:
print(cars)
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:
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?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
x = cars[0]
x = cars[0]
print(x)
Example
Modify the value of the first array item:
cars[0] = "Toyota"
cars = ["Ford", "Volvo", "BMW"] ['Toyota', 'Volvo', 'BMW']
cars[0] = "Toyota"
print(cars)
Example
Return the number of elements in the cars array:
x = len(cars)
x = len(cars)
print(x)
Note: The length of an array is always one more than the highest array index.
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example
Print each item in the cars array:
for x in cars:
print(x)
cars = ["Ford", "Volvo", "BMW"] Ford
Volvo
for x in cars: BMW
print(x)
Example
Add one more element to the cars array:
cars.append("Honda")
cars.append("Honda")
print(cars)
Example
Delete the second element of the cars array:
cars.pop(1)
cars = ["Ford", "Volvo", "BMW"] ['Ford', 'BMW']
cars.pop(1)
print(cars)
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")
cars.remove("Volvo")
print(cars)
Note: The remove() method only removes the first occurrence of the specified
value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the curren
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be
used instead.
print(fruits)
Syntax
list.append(elmnt)
Parameter Values
Parameter Description
a.append(b)
print(a)
fruits.clear()
print(fruits)
Syntax
list.clear()
Parameter Values
No parameters
Python List copy() Method
Example
Copy the fruits list:
x = fruits.copy()
fruits = ["apple", "banana", "cherry"] ['apple', 'banana', 'cherry']
x = fruits.copy()
print(x)
Syntax
list.copy()
Parameter Values
No parameters
x = fruits.count("cherry")
fruits = ["apple", "banana", "cherry"] 1
x = fruits.count("cherry")
print(x)
Example
Return the number of times the value 9 appears int the list:
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x =
points.count(9)
fruits = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = fruits.count(9) 2
print(x)
Syntax
list.extend(iterable)
Example
Add a tuple to the fruits list:
points = (1, 4, 5, 9)
fruits.extend(points)
fruits = ['apple', 'banana', 'cherry'] ['apple', 'banana', 'cherry', 1, 4,
5, 9]
points = (1, 4, 5, 9)
fruits.extend(points)
print(fruits)
x = fruits.index("cherry")
fruits = ['apple', 'banana', 'cherry'] 2
x = fruits.index("cherry")
print(x)
Example
What is the position of the value 32:
x = fruits.index(32)
fruits = [4, 55, 64, 32, 16, 32] 3
x = fruits.index(32)
print(x)
Note: The index() method only returns the first occurrence of the value.
fruits.insert(1, "orange")
fruits = ['apple', 'banana', 'cherry'] ['apple', 'orange', 'banana',
'cherry']
fruits.insert(1, "orange")
print(fruits)
Syntax
list.insert(pos, elmnt)
fruits.pop(1)
print(fruits)
Syntax
list.pop(pos)
Example
Return the removed element:
x = fruits.pop(1)
x = fruits.pop(1)
print(x)
Note: The pop() method returns removed value.
Python List remove() Method
Example
Remove the "banana" element of the fruit list:
fruits.remove("banana")
fruits.remove("banana")
print(fruits)
fruits.reverse()
print(fruits)
Python List sort() Method
Definition and Usage
The sort() method sorts the list ascending by default.
cars.sort()
print(cars)
Sort the list descending:
cars = ['Ford', 'BMW', 'Volvo'] ['Volvo', 'Ford', 'BMW']
cars.sort(reverse=True)
print(cars)
cars.sort(key=myFunc)
print(cars)
cars.sort(key=myFunc)
print(cars)
cars.sort(reverse=True, key=myFunc)
print(cars)
Python Classes/Objects
Python is an object oriented programming language.
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
class MyClass: <class '__main__.MyClass'>
x=5
print(MyClass)
Create Object
Now we can use the class named myClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass() print(p1.x)
class MyClass: 5
x=5
p1 = MyClass() print(p1.x)
All classes have a function called __init__(), which is always executed when the
class is being initiated.
Example
Create a class named Person, use the __init__() function to assign values for
name and age:
class Person: John
def __init__(self, name, age): 36
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belongs
to the object.
Example
Insert a function that prints a greeting, and execute it on the p1 object:
Note:
p1 = Person("John", 36)
p1.myfunc()
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has
to be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Example
Set the age of p1 to 40:
p1.age = 40
class Person: 40
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
Example
Delete the age property from the p1 object: del
p1.age
class Person: def Traceback (most recent call last):
__init__(self, name, age): File "demo_class7.py", line 13,
self.name = name
in <module>
self.age = age
print(p1.age)
def myfunc(self): AttributeError: 'Person' object has
print("Hello my name is " + self.name) no attribute 'age'
p1 = Person("John", 36)
del p1.age
print(p1.age)
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
class Person: def Traceback (most recent call last):
__init__(self, name, age): File "demo_class8.py", line 13,
self.name = name
in <module>
self.age = age
print(p1)
def myfunc(self): NameError: 'p1' is not defined
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1
print(p1)
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
Example
Create a class named Person, with firstname and lastname properties, and a
printname method:
John Doe
class Person: def __init__(self,
fname, lname): self.firstname =
fname self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties
or methods to the class.
Now the Student class has the same properties and methods as the Person
class.
class Person: def __init__(self, Mike Olsen
fname, lname): self.firstname =
fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
Add the __init__() Function
So far we have created a child class that inherits the properties and methods
from its parent.
We want to add the __init__() function to the child class (instead of the
pass keyword).
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person): def
__init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
x.printname()
Now we have successfully added the __init__() function, and kept the
inheritance of the parent class, and we are ready to add functionality in
the __init__() function.
Add Properties
Example
Add a property called graduationyear to the Student class:
class Person: def __init__(self, 2019
fname, lname): self.firstname =
fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Student("Mike", "Olsen")
print(x.graduationyear)
In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another
parameter in the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Person: def __init__(self, 2019
fname, lname): self.firstname =
fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
def printname(self):
print(self.firstname, self.lastname)
Python Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable
containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
Example
Return an iterator from a tuple, and print each value:
mytuple = ("apple", "banana", "cherry") apple
myit = iter(mytuple) banana
cherry
print(next(myit))
print(next(myit))
print(next(myit))
Even strings are iterable objects, and can return an iterator:
Example
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana" b
myit = iter(mystr) a
n
print(next(myit)) a
print(next(myit)) n
print(next(myit)) a
print(next(myit))
print(next(myit))
print(next(myit))
Example
Iterate the values of a tuple:
mytuple = ("apple", "banana", "cherry") apple
banana
for x in mytuple: cherry
print(x)
Example
Iterate the characters of a string:
mystr = "banana" b
a
for x in mystr: n
print(x) a
n
a
The for loop actually creates an iterator object and executes the next() method
for each loop.
Create an Iterator
To create an object/class as an iterator you have to implement the methods
__iter__() and __next__() to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you do some initializing when the
object is being created.
The __iter__() method acts similar, you can do operations (initializing etc.),
but must always return the iterator object itself.
The __next__() method also allows you to do operations, and must return the
next item in the sequence.
Example
Create an iterator that returns numbers, starting with 1, and each sequence will
increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers: 1
def __iter__(self): 2
self.a = 1 3
return self 4
5
def __next__(self):
x = self.a self.a +=
1
return x
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
StopIteration
The example above would continue forever if you had enough next()
statements, or if it was used in a for loop.
Example
Stop after 20 iterations:
class MyNumbers: 1
def __iter__(self): 2
self.a = 1 3
return self 4
5
def __next__(self): 6
if self.a <= 20: 7
8
9
x = self.a 10
self.a += 1 11
return x else: 12
raise StopIteration 13
14
myclass = MyNumbers() 15
myiter = iter(myclass) 16
17
for x in myiter: 18
print(x) 19
20
Python Modules
What is a Module?
Consider a module to be the same as a code library.
Create a Module
To create a module just save the code you want in a file with the file extension
.py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule Hello, Jonathan
mymodule.greeting("Jonathan")
Note: When using a function from a module, use the
syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway" }
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule 36
a = mymodule.person1["age"] print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx 36
a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.
Example
Import and use the platform module:
import platform Windows
x = platform.system()
print(x)
Example
List all the defined names belonging to the platform module:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway" }
Example
Import only the person1 dictionary from the module:
from mymodule import person1 36
print(person1["age"])
Note: When importing using the from keyword, do not use the module name
when referring to elements in the module.
Example: person1["age"], notmymodule.person1["age"]
Python Datetime
Python Dates
A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.
Example
Import the datetime module and display the current date:
import datetime 2019-05-04 20:17:38.287031
x = datetime.datetime.now()
print(x)
Date Output
When we execute the code from the example above the result will be:
2019-05-04 20:16:30.617974
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date
object.
Here are a few examples, you will learn more about them later in this chapter:
Example
Return the year and name of weekday:
import datetime 2019
Saturday
x = datetime.datetime.now()
print(x.year) print(x.strftime("%A"))
The datetime() class requires three parameters to create a date: year, month,
day.
Example
Create a date object:
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour,
minute, second, microsecond, tzone), but they are optional, and has a default
value of 0, (None for timezone).
The strftime() Method
The datetime object has a method for formatting date objects into readable
strings.
The method is called strftime(), and takes one parameter, format, to specify
the format of the returned string:
import datetime June
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Python JSON
JSON is a syntax for storing and exchanging data.
JSON in Python
Python has a built-in package called json, which can be used to work with JSON
data.
Example
Import the json module:
import json
Example
Convert from JSON to Python:
import json 30
# some JSON:
x = '{ "name":"John", "age":30, "city":"New
York"}'
# parse x:
y = json.loads(x)
Example
Convert from Python to JSON:
import json {"name": "John", "age": 30, "city":
"New York"}
# a Python object (dict):
x={
"name": "John",
"age": 30,
"city": "New York"
}
• dict
• list
• tuple
• string
• int
• float
• True
• False • None
Example
Convert Python objects into JSON strings, and print the values:
import json {"name": "John", "age": 30}
["apple", "bananas"]
print(json.dumps({"name": "John", "age": 30})) ["apple", "bananas"]
print(json.dumps(["apple", "bananas"])) "hello"
print(json.dumps(("apple", "bananas"))) 42
print(json.dumps("hello")) 31.76
print(json.dumps(42)) true
print(json.dumps(31.76))
false
print(json.dumps(True))
print(json.dumps(False)) null
print(json.dumps(None))
When you convert from Python to JSON, Python objects are converted into the
JSON (JavaScript) equivalent:
Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
Example
Convert a Python object containing all the legal data types:
import json {"name": "John", "age": 30,
"married": true, "divorced": false,
x={ "children": ["Ann","Billy"],
"name": "John",
"pets": null, "cars": [{"model":
"age": 30,
"married": True, "BMW 230", "mpg": 27.5}, {"model":
"divorced": False, "Ford Edge", "mpg": 24.1}]}
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
The json.dumps() method has parameters to make it easier to read the result:
Example
Use the indent parameter to define the numbers of indents:
json.dumps(x, indent=4)
import json {
"name": "John",
x={ "age": 30,
"name": "John", "married": true,
"age": 30,
"divorced": false,
"married": True,
"divorced": False,
"children": [
"children": ("Ann","Billy"), "Ann",
"pets": None, "Billy"
"cars": [ ],
{"model": "BMW 230", "mpg": 27.5}, "pets": null,
{"model": "Ford Edge", "mpg": 24.1}
"cars": [
]
{
}
"model": "BMW 230",
# use four indents to make it easier to read the "mpg": 27.5
result: },
print(json.dumps(x, indent=4)) {
"model": "Ford Edge",
"mpg": 24.1
}
]
}
You can also define the separators, default value is (", ", ": "), which means
using a comma and a space to separate each object, and a colon and a space to
separate keys from values:
Example
Use the separators parameter to change the default separator:
import json {
"name" = "John".
x={ "age" = 30.
"name": "John",
"married" = true.
"age": 30,
"married": True,
"divorced" = false.
"divorced": False, "children" = [
"children": ("Ann","Billy"), "Ann".
"pets": None, "Billy"
"cars": [ ],
{"model": "BMW 230", "mpg": 27.5},
"pets" = null.
{"model": "Ford Edge", "mpg": 24.1}
"cars" = [
] {
} "model" = "BMW 230".
"mpg" = 27.5
# use . and a space to separate objects, and a
}.
space, a = and a space to separate keys from
{
their values: print(json.dumps(x, indent=4,
separators=(". ", " = "))) "model" = "Ford Edge".
"mpg" = 24.1
}
]
}
Example
Use the sort_keys parameter to specify if the result should be sorted or not: