03 PythonBasics Loops Function PDF
03 PythonBasics Loops Function PDF
03 PythonBasics Loops Function PDF
Loops
In programming, looping means repeating the same set of computations in the same sequence for a number of times.
Think about a real-life situation. You are a field biologist who’s taking measurements of trees in the forest. You pick a tree, measure its diameter and height, write them down in your
notebook and make an estimate of its total volume. Next, you pick another tree, measure its diameter and height, write them down in your notebook and make an estimate of its total
volume. Then, you pick yet another tree, measure its diameter and height, write them down in your notebook and make an estimate of its total volume. You keep repeating the same
process until all trees in the sample are exhausted. In programming lingo, you are looping over each tree and doing the same set of tasks in the same sequence.
1. for loops iterate a finite number of times for each element in the iterable object
For Loops
This loop is used for iterating over some kind of a sequence. That can be a list, tuple, dictionary, string, etc.
101
102
103
104
105
In [5]: new_list = []
list1 = [2, 3, 4]
list2 = [4, 5, 6]
for i in list1:
for j in list2:
new_list.append(i*j)
In [6]: print(new_list)
Dictionaries in Python are a collection of key-value pairs — meaning, every item in the dictionary has a key and an associated value. You can loop over these dictionary
elements and do a variety of operations.
In [7]: football_players_dict = {
"Son": "Tottenham",
"Kang-in": "Mallorca",
"Messi": "Barcelona",
"Mbappé": "Paris Saint-Germain",
"Kane": "Tottenham"
}
Son
Kang-in
Messi
Mbappé
Kane
Tottenham
Mallorca
Barcelona
Paris Saint-Germain
Tottenham
P
y
t
h
o
n
I
love
Text
Mining
While Loops
Like for loops, while loops repeatedly execute a block of code — as long as a condition is true. The loop only breaks out once the looping condition is false.
In [15]: i = 0
while i <=5:
print(i)
i = i+1 # option to break out of the loop
0
1
2
3
4
5
2. Functions
Define a function without parameters
define a function with def
comes the name of the function
e.g.,
print_hello_world()
no parameters passed to a function
In [5]: print_hello_world()
Hello world
The position is of importance when passing positional parameters. Note that we need to pass the two required parameters here. Otherwise, we will get a TypeError
indicating that we have passed an incorrect number of parameters
In [12]: integer_division(10, 2)
5.0
Out[12]: