0% found this document useful (0 votes)
2 views50 pages

Python PDF

The document provides an overview of Python conditions, if statements, loops, and functions. It explains the use of logical operators, control flow statements like if, elif, and else, as well as the functionality of while and for loops. Additionally, it covers the creation and usage of functions, recursion, and arrays/lists in Python, including methods for manipulating them.

Uploaded by

Ayushi Gon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views50 pages

Python PDF

The document provides an overview of Python conditions, if statements, loops, and functions. It explains the use of logical operators, control flow statements like if, elif, and else, as well as the functionality of while and for loops. Additionally, it covers the creation and usage of functions, recursion, and arrays/lists in Python, including methods for manipulating them.

Uploaded by

Ayushi Gon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Python

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

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.

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".

You can also have an else without the eli :


f
a = 200 b is not greater than a
b = 33
if b > a:
print("b is greater than a")
else: print("b is not greater
than a")

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

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:
a=2 B
b = 330

print("A") if a > b else print("B")

ou can also have multiple else statements on the same line:

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")

The while Loop


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

Print i as long as i is less than 6:


i = 1 while 1
i < 6: 2
print(i) 3
i += 1 4
5

The break Statement


With the break statement we can stop the loop even if the while condition is
true:
i = 1 while 1
i < 6: 2
print(i) 3
if (i == 3):
break i
+= 1

The continue Statement


With the continue statement we can stop the current iteration, and continue
with the next:
i = 0 while 1
i < 6: 2
i += 1 if i 4
== 3: 5
continue 6
print(i)

# Note that number 3 is missing in the result

The else Statement


With the else statement we can run a block of code once when the condition no
longer 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

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:
for x in "banana": b
print(x) a
n
a
n
a

The break Statement


With the break statement we can stop the loop before it has looped through all
the items:
fruits = ["apple", "banana", "cherry"] apple
for x in fruits: banana
print(x) if x ==
"banana":
break
Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", apple
"cherry"] for x in fruits: if x ==
"banana":
break
print(x)

The continue Statement


With the continue statement we can stop the current iteration of the loop, and
continue with the next:
fruits = ["apple", "banana", apple
"cherry"] for x in fruits: if x == cherry
"banana": continue print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the
range() function,

The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and ends at a specified number.

Using the range() function:


for x in range(6): 0
print(x) 1
2
3
4
5

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it


is possible to range(2, 6)
specify the starting value by adding a parameter: , which means
values from 2 to 6 (but not including 6):
Using the start parameter:
for x in range(2, 6): 2
print(x) 3
4
5
The range() function defaults to increment the sequence by 1, however it is
possible to specify the increment value by adding a third parameter: range(2,
30, 3):
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3): 2
print(x) 5
8
11
14
17
20
23
26
29

Else in For Loop


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

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":

Print each adjective for every fruit:


adj = ["red", "big", "tasty"] red apple
fruits = ["apple", "banana", "cherry"] red banana
red cherry
for x in adj: big apple
for y in fruits:
print(x, y)
big banana
big cherry
tasty apple
tasty banana
tasty cherry

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.

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")

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:


def my_function(country = "Norway"): I am from Sweden
print("I am from " + country) I am from India
I am from Norway
my_function("Sweden")
I am from Brazi
my_function("India")
my_function()
my_function("Brazil")

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.

Recursion is a common mathematical and programming concept. It means that


a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

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

print("\n\nRecursion Example Results")


tri_recursion(6)
Python Arrays
Arrays
Arrays are used to store multiple values in one single variable:

Example
Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

cars = ["Ford", "Volvo", "BMW"] ['Ford', 'Volvo', 'BMW']

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:

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]

cars = ["Ford", "Volvo", "BMW"] Ford

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)

The Length of an Array


Use the len() method to return the length of an array (the number of elements
in an array).

Example
Return the number of elements in the cars array:
x = len(cars)

cars = ["Ford", "Volvo", "BMW"] 3

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)

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")

cars = ["Ford", "Volvo", "BMW"] ['Ford', 'Volvo', 'BMW', 'Honda']

cars.append("Honda")

print(cars)

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)
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 = ["Ford", "Volvo", "BMW"] ['Ford', 'BMW']

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

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

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

Python List append() Method


Example
Add an element to the fruits list:

fruits = ['apple', 'banana', 'cherry'] fruits.append("orange")


fruits = ["apple", "banana", "cherry"] ['apple', 'banana', 'cherry',
'orange']
fruits.append("orange")

print(fruits)

Definition and Usage


The append() method appends an element to the end of the list.

Syntax
list.append(elmnt)

Parameter Values

Parameter Description

elmnt Required. An element of any type (string, number, object


etc.)

Add a list to a list:

More Examples Example

a = ["apple", "banana", "cherry"] b


= ["Ford", "BMW", "Volvo"]
a.append(b)
a = ["apple", "banana", "cherry"] ['apple', 'banana', 'cherry',
["Ford", "BMW", "Volvo"]]
b = ["Ford", "BMW", "Volvo"]

a.append(b)

print(a)

Python List clear() Method


Example
Remove all elements from the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']


fruits.clear()
fruits = ["apple", "banana", "cherry"] []

fruits.clear()

print(fruits)

Definition and Usage


The clear() method removes all the elements from a list.

Syntax
list.clear()

Parameter Values
No parameters
Python List copy() Method
Example
Copy the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']

x = fruits.copy()
fruits = ["apple", "banana", "cherry"] ['apple', 'banana', 'cherry']

x = fruits.copy()

print(x)

Definition and Usage


The copy() method returns a copy of the specified list.

Syntax
list.copy()

Parameter Values
No parameters

Python List count() Method


Example
Return the number of times the value "cherry" appears int the fruits list:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")
fruits = ["apple", "banana", "cherry"] 1

x = fruits.count("cherry")

print(x)

Definition and Usage


The count() method returns the number of elements with the specified value.

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)

Python List extend() Method


Example
Add the elements of cars to the fruits list:

fruits = ['apple', 'banana', 'cherry']

cars = ['Ford', 'BMW', 'Volvo']


fruits.extend(cars)

Definition and Usage


The extend() method adds the specified list elements (or any iterable) to the
end of the current list.

Syntax
list.extend(iterable)
Example
Add a tuple to the fruits list:

fruits = ['apple', 'banana', 'cherry']

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)

Python List index() Method


Example
What is the position of the value "cherry":

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")
fruits = ['apple', 'banana', 'cherry'] 2

x = fruits.index("cherry")

print(x)

Definition and Usage


The index() method returns the position at the first occurrence of the specified
value.
Syntax
list.index(elmnt)

Example
What is the position of the value 32:

fruits = [4, 55, 64, 32, 16, 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.

Python List insert() Method


Example
Insert the value "orange" as the second element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")
fruits = ['apple', 'banana', 'cherry'] ['apple', 'orange', 'banana',
'cherry']
fruits.insert(1, "orange")

print(fruits)

Definition and Usage


The insert() method inserts the specified value at the specified position.

Syntax
list.insert(pos, elmnt)

Python List pop() Method


Example
Remove the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
fruits = ['apple', 'banana', 'cherry'] ['apple', 'cherry']

fruits.pop(1)

print(fruits)

Definition and Usage


The pop() method removes the element at the specified position.

Syntax
list.pop(pos)

Example
Return the removed element:

fruits = ['apple', 'banana', 'cherry']

x = fruits.pop(1)

fruits = ['apple', 'banana', 'cherry'] banana

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 = ['apple', 'banana', 'cherry']

fruits.remove("banana")

Definition and Usage


The remove() method removes the first occurrence of the element with the
specified value.

fruits = ['apple', 'banana', 'cherry'] ['apple', 'cherry']

fruits.remove("banana")

print(fruits)

Python List reverse() Method


Definition and Usage
The reverse() method reverses the sorting order of the elements.
fruits = ['apple', 'banana', 'cherry'] ['cherry', 'banana', 'apple']

fruits.reverse()

print(fruits)
Python List sort() Method
Definition and Usage
The sort() method sorts the list ascending by default.

You can also make a function to decide the sorting criteria(s).

Sort the list alphabetically:


cars = ['Ford', 'BMW', 'Volvo'] ['BMW', 'Ford', 'Volvo']

cars.sort()

print(cars)
Sort the list descending:
cars = ['Ford', 'BMW', 'Volvo'] ['Volvo', 'Ford', 'BMW']

cars.sort(reverse=True)

print(cars)

Sort the list by the length of the values:


# A function that returns the length of the ['VW', 'BMW', 'Ford', 'Mitsubishi']
value: def myFunc(e): return len(e)

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']

cars.sort(key=myFunc)

print(cars)

Sort a list of dictionaries based on the "year" value of the dictionaries:


# A function that returns the 'year' [{'car': 'Mitsubishi', 'year':
value: def myFunc(e): return e['year'] 2000}, {'car': 'Ford', 'year':
2005}, {'car': 'VW', 'year': 2011},
cars = [
{'car': 'BMW', 'year': 2019}]
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]

cars.sort(key=myFunc)

print(cars)

Sort the list by the length of the values and reversed:


# A function that returns the length of the ['Mitsubishi', 'Ford'', 'BMW',
value: def myFunc(e): return len(e) 'VW']

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']

cars.sort(reverse=True, key=myFunc)

print(cars)

Python Classes/Objects
Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

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)

The __init__() Function


The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.

To understand the meaning of classes we have to understand the built-in


__init__() function.

All classes have a function called __init__(), which is always executed when the
class is being initiated.

Use the __init__() function to assign values to object properties, or other


operations that are necessary to do when the object is being created:

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.

Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:

class Person: def


__init__(self, name, age):
self.name = name
self.age = age
def
myfunc(self):
print("Hello my name is " + self.name)

Note:
p1 = Person("John", 36)
p1.myfunc()

class Person: Hello my name is John


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.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.

The self Parameter


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:

class Person: def


__init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age def
myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John",
36) p1.myfunc()
class Person: def Hello my name is John
__init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties


You can modify properties on objects like this:

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)

Delete Object Properties


You can delete properties on objects by using the del keyword:

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.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other
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)

#Use the Person class to create an object, and


then execute the printname method:

x = Person("John", "Doe")
x.printname()

Create a Child Class


To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods
from the Person class:

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.

Note: The child's __init__() function overrides the inheritance of the


parent's __init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

class Person: Mike Olsen


def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

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)

class Student(Person): def


__init__(self, fname, lname):
Person.__init__(self, fname, lname)
self.graduationyear = 2019

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)

class Student(Person): def


__init__(self, fname, lname, year):
Person.__init__(self, fname, lname)
self.graduationyear = year

x = Student("Mike", "Olsen", 2019)


print(x.graduationyear)
Add Methods
Example
Add a method called welcome to the Student class:
class Person: def __init__(self, Welcome Mike Olsen to the class of
fname, lname): self.firstname = 2019
fname self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

class Student(Person): def


__init__(self, fname, lname, year):
Person.__init__(self, fname, lname)
self.graduationyear = year

def welcome(self): print("Welcome",


self.firstname, self.lastname,
"to the class of", self.graduationyear)

x = Student("Mike", "Olsen", 2019)


x.welcome()
If you add a method in the child class with the same name as a function in the
parent class, the inheritance of the parent method will be overridden.

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.

Technically, in Python, an iterator is an object which implements the iterator


protocol, which consist of the methods __iter__() and __next__().

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))

Looping Through an Iterator


We can also use a for loop to iterate through an iterable object:

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

myclass = MyNumbers() myiter


= iter(myclass)

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.

To prevent the iteration to go on forever, we can use the


StopIteration statement.
In the __next__() method, we can add a terminating condition to raise an error
if the iteration is done a specified number of times:

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.

A file containing a set of functions you want to include in your application.

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)

Using the dir() Function


There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:

Example
List all the defined names belonging to the platform module:

import platform ['DEV_NULL', '_UNIXCONFDIR',


'WIN32_CLIENT_RELEASES', x = dir(platform)
'WIN32_SERVER_RELEASES', print(x) '__builtins__',
'__cached__',
'__copyright__', '__doc__',
'__file__', '__loader__',
'__name__', '__package __',
'__spec__', '__version__',
'_default_architecture', 'uname',
'uname_result', 'version',
'warnings', 'win32_ver']
Note: The dir() function can be used on all modules, also the ones you create
yourself.

Import From Module


You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:

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"))

Creating Date Objects


To create a date, we can use the datetime() class (constructor) of
the datetime module.

The datetime() class requires three parameters to create a date: year, month,
day.

Example
Create a date object:

import datetime 2020-05-17 00:00:00

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 is text, written with JavaScript object notation.

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

Parse JSON - Convert from JSON to Python


If you have a JSON string, you can parse it by using the json.loads() method.

The result will be a Python dictionary.

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)

# the result is a Python dictionary:


print(y["age"])

Convert from Python to JSON


If you have a Python object, you can convert it into a JSON string by using the
json.dumps() method.

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"
}

# convert into JSON:


y = json.dumps(x)

# the result is a JSON string:


print(y)
You can convert Python objects of the following types, into JSON strings:

• 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}
]
}

# convert into JSON: y =


json.dumps(x)

# the result is a JSON string: print(y)

Format the Result


The example above prints a JSON string, but it is not very easy to read, with no
indentations and line breaks.

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
}
]
}

Order the Result


The json.dumps() method has parameters to order the keys in the result:

Example
Use the sort_keys parameter to specify if the result should be sorted or not:

json.dumps(x, indent=4, sort_keys=True)


import json {
"age": 30,
x={ "cars": [
"name": "John",
{
"age": 30,
"model": "BMW 230",
"married": True,
"divorced": False, "mpg": 27.5
"children": ("Ann","Billy"), },
"pets": None, {
"cars": [ "model": "Ford Edge",
{"model": "BMW 230", "mpg": 27.5}, "mpg": 24.1
{"model": "Ford Edge", "mpg": 24.1}
}
]
],
}
# sort the result alphabetically by keys: "children": [
print(json.dumps(x, indent=4, sort_keys=True)) "Ann",
"Billy"
],
"divorced": false,
"married": true,
"name": "John",
"pets": null
}

You might also like