python - loops · the while loop jan hnilica computer modelling 4 3 • there can be a block of...
TRANSCRIPT
Jan Hnilica Computer modelling 4 1
Python - loops
Loops
2 Jan Hnilica Computer modelling 4
• loops allow to repeatedly execute a statement (or a block of statements) as long as a condition remains True
• there are 2 types of loops in the Python language: • the while loop • the for loop
before the loop
statements of the loop
after the loop
condition
True
False
The while loop
3 Jan Hnilica Computer modelling 4
• there can be a block of statements instead of a single statement • the else statement (in the second example) is not obligatory
(it is executed when the condition becomes False) • the condition is tested before the first iteration
⇒ if it evaluates False, no iteration is executed
while condition: statement
while condition: statement1 else statement2
x = 1 while x <= 5: print(x) x = x + 1
output: 1 2 3 4 5
The while loop examples
4 Jan Hnilica Computer modelling 4
number = 2 while number % 2 == 0: number = int(input("set an odd number: ")) print("thanks, you have set", number)
N = int(input("set a number: ")) x = 1 SUM = 0 while x <= N: SUM = SUM + x x = x + 1 print("sum 1 :", N, "is", SUM)
output: set a number: 25 sum 1 : 25 is 325
• calculation of the sum of 1 : N
• communication with the user until an odd number is obtained:
The for loop
5 Jan Hnilica Computer modelling 4
for variable in object: statement
• the object • must be iterable – it must be composed from elements, which are
accessible through indices in square brackets • example of such object is a string (composed from individual characters)
• in individual iterations the elements of the object are copied one by one to the variable; the variable is then accessible in the statement
• the block of statements can be used as well
for variable in object: statement1 else statement2
string = "hello" for i in string: print(i)
output: h e l l o
The function range
6 Jan Hnilica Computer modelling 4
range(x)
• returns a sequence of integers, which can be used as an object in the for loop • there are 3 possible ways how to call the function:
returns the sequence from 0 to (x – 1)
for i in range(5): print(i, end = " ")
0 1 2 3 4 ⇒
range(x, y) returns the sequence from x to (y – 1)
for i in range(5, 11): print(i, end = " ")
5 6 7 8 9 10 ⇒
range(x, y, step) returns the sequence from x to (y – 1) with a given step
for i in range(0, 11, 2): print(i, end = " ")
0 2 4 6 8 10 ⇒
Note: the function range returns an object of the class range (we will learn about classes later…)
The for loop examples
7 Jan Hnilica Computer modelling 4
N = int(input("set a number: ")) SUM = 0 for i in range(1, N + 1): SUM += i print("sum 1 :", N, "is", SUM)
• calculation of a sum from 1 to N:
n = int(input("set a number: ")) factorial = 1 for i in range(2, n + 1): factorial *= i print("factorial:", factorial)
• calculation of a factorial
Nested loops
8 Jan Hnilica Computer modelling 4
• any loop can be nested in a body of another one • the following example prints the square to the screen:
width = 10 length = 5 for i in range(length): # outer for j in range(width): # inner print("*", end = "") print() # new line
• at each iteration of the outer loop all its statements are executed: 1. the full inner loop 2. the print of the new line
• levels of nesting are given by an indentation ⇒ therefore the print of the new line is subordinated to the outer loop
********** ********** ********** ********** **********
⇒
Nested loops
9 Jan Hnilica Computer modelling 4
• three levels of nesting: number_of_squares = 3 width = 10 length = 5 for i in range(number_of_squares): for j in range(length): for k in range(width): print("*", end = "") print() # new row print() # a space between squares
********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** **********
⇒
The break statement
10 Jan Hnilica Computer modelling 4
• allows to immediately exit the loop (regardless of a driving condition) • when the break statement is reached, the program exits the loop, all remaining
statements of the loop are skipped and the program continues with the first statement after the loop
• the break statement is always connected with a condition Example
• the loop works with keyboard input • the input 0 is a signal to finish the loop
while True: # the never-ending loop (can be interrupted only by break) x = int(input()) if x == 0: break # exit the loop else: ... # do something with x how to write such loop without the break?
The continue statement
11 Jan Hnilica Computer modelling 4
• allows to immediately finish the actual iteration • when the continue statement is reached, the actual iteration is finished, all
remaining statements of the loop are skipped and the program continues with the condition testing in the top of the loop
• the continue statement is always connected with a condition Example
• the loop reads a number x from the keyboard and prints the value (1/x) • the input -1 is a signal to finish the loop
x = 1 # initial value (in order to get into the loop) while x != -1: x = int(input()) if x == 0: print("division by zero is illegal!!!") continue print(1/x)
Notes to the break and continue statements
12 Jan Hnilica Computer modelling 4
• if the loop has the else branch, it is not executed, if the loop is finished by the break statement
• both break and continue statements are quite dangerous and should be used with caution and after some consideration
• both these statements make the loop hard to read and understand, as they cause sudden jumps in the program flow
• often it is better to use the if statement to skip some lines within a body of loop than to use the continue statement
• the break statement can often be replaced by better formulation of a driving condition
The pass statement
13 Jan Hnilica Computer modelling 4
• null statement, it means “do nothing” • sometimes it is useful (sometimes it is even necessary)
if condition: ... # do something else pass # do nothing
List
14 Jan Hnilica Computer modelling 4
• compound data type, containing an ordered sequence of variables • example: list my_list containing integers 5, 8, 2, 7, 9
my_list 5 8 2 7 9 index 0 1 2 3 4
element my_list[0] my_list[1] my_list[2] my_list[3] my_list[4]
• individual elements are accessible through a name of a list followed by an index in square brackets: list_name[index]
Basic rules: • indices always start from 0 • a list containing N elements has indices from 0 to (N – 1)
Creation of a list
15 Jan Hnilica Computer modelling 4
• manually, using the square brackets my_list = [] # an empty list my_list = [4, 5, 7, 1, 3] # a list containing integers my_list = [4, "hello", 2.133] # a list composed from different data types
• using the list function my_list = list() # empty list
• the list function can take one argument – an iterable object (the elements of a new list are created from the elements of the object)
my_list = list(range(10)) # list containing integers 0 – 9 my_list = list("hello") # list containing the characters of the string
Working with lists
16 Jan Hnilica Computer modelling 4
• accessing elements from the end using negative indices
my_list = list("abc") print(my_list[-1], my_list[-2])
⇒ c b
• individual elements of a list are mutable (contrary to the string data type)
my_list = list("abc") my_list[0] = "A" print(my_list)
⇒ ['A', 'b', 'c']
• a list can be printed using the print function
my_list = list("abc") print(my_list)
⇒ ['a', 'b', 'c']
• a whole list can be multiplied by * operator (it returns a new list variable)
my_list = list("abc") new_list = my_list * 2 print(new_list)
⇒ ['a', 'b', 'c', 'a', 'b', 'c']
Working with lists
17 Jan Hnilica Computer modelling 4
• a slice from the list • my_list[x:y] returns a list containing the elements from x to (y – 1) • my_list[x:y:z] returns a list containing the elements from x to y with a step z
my_list = list(range(10)) print(my_list) my_list_2 = my_list[0:3] print(my_list_2) my_list_3 = my_list[0:10:2] print(my_list_3)
⇒ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2] [0, 2, 4, 6, 8]
• any of indices in a slice can be omitted
my_list_2 = my_list[::3] print(my_list_2)
⇒ [0, 3, 6, 9]
each third from the beginning to the end
Functions working with lists
18 Jan Hnilica Computer modelling 4
• the functions are called using a syntax: function(list) • these functions can work even with other data structures
len(my_list) # returns a number of elements min(my_list) # returns a minimum value max(my_list) # returns a maximum value sum(my_list) # returns a sum of elements sorted(my_list) # return sorted copy of list (does not modify the original) all(my_list) # returns True if all of elements evaluates to True any(my_list) # returns True if at least one of elements evaluates to True
List methods
19 Jan Hnilica Computer modelling 4
• in general - methods are the functions of a particular class • the methods of the class list are called using a syntax: list.method() • some of the list methods:
my_list.append(x)
• appends a variable x to the end of the list my_list.pop()
• returns the last element of a list (the element is removed from the list) my_list.pop(i)
• removes and returns i-th element my_list.sort()
• sorts the elements my_list.clear()
• removes all elements
(you will learn about classes later)
List methods
20 Jan Hnilica Computer modelling 4
# code ml = list() for i in range(10, 0, -1): ml.append(i) print("original:", ml) ml.sort() print("sorted:", ml) for i in range(len(ml)): print("pop:", ml.pop())
# output original: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] sorted: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] pop: 10 pop: 9 pop: 8 pop: 7 pop: 6 pop: 5 pop: 4 pop: 3 pop: 2 pop: 1
Passing through list elements
21 Jan Hnilica Computer modelling 4
ml = list(range(5)) for i in ml: print(i)
• typically the for loop is used
• the elements can be modified in this way
0 1 2 3 4
⇒
ml = [8, 4, 3] print(ml) for i in range(len(ml)): ml[i] = ml[i] + 1 print(ml)
⇒ [8, 4, 3] [9, 5, 4]
Passing through list elements
22 Jan Hnilica Computer modelling 4
ml = list(range(5)) index = 0 while index < len(ml): print(ml[index]) index += 1
• the while loop can be used as well
0 1 2 3 4
⇒
Deletion elements
23 Jan Hnilica Computer modelling 4
ml = list(range(5)) print(ml) del ml[1] # the same as ml.pop(1) print(ml)
• function del my_list[i] deletes the i-th element
[0, 1, 2, 3, 4] [0, 2, 3, 4] ⇒
• the slice can be deleted as well
ml = list(range(5)) print(ml) del ml[0:3] # deletes the first two elements print(ml) [0, 1, 2, 3, 4]
[3, 4] ⇒
2D list (matrix)
24 Jan Hnilica Computer modelling 4
• = list of lists (list, whose elements are lists)
Example: matrix 3 × 4: 1 2 7 5
9 6 3 8
3 4 2 5
is in Python represented:
1 2 7 5
9 6 3 8
3 4 2 5
# manual creation matrix = [[1, 2, 7, 5], [9, 6, 3, 8], [3, 4, 2, 5]]
matrix[0][0] matrix[0][3]
matrix[2][3]
matrix[0]
matrix[1]
matrix[2]
Creation of a matrix of size m×n
25 Jan Hnilica Computer modelling 4
• creation of a matrix m×n filled with zeros
# solution 1 matrix = [] for i in range(m): temp = [] # temporary list for j in range(n): temp.append(0) matrix.append(temp) # solution 2 matrix = [] for i in range(m): matrix.append([0] * n) # use of multiplied list
m
n
Creation of a matrix of size m×n
26 Jan Hnilica Computer modelling 4
This solution does not work:
# solution 3 matrix = [[0] * n] * m
m
n
Reason: [0] * n is only a reference to a list, therefore the matrix now contains three references to the same list (if you set matrix[0, 0] = 1, also matrix[1, 0] and matrix[2, 0] will be 1)
Passing through a matrix
27 Jan Hnilica Computer modelling 4
• incrementing of all elements by 1
for i in range(m): for j in range(n): matrix[i][j] += 1
m
n
• sum of individual elements
s = 0 for i in range(m): for j in range(n): s += matrix[i][j]
Conclusion
28 Jan Hnilica Computer modelling 4
• more information about the list methods can be obtained by typing
help(list)
• a complete enumeration of all functions of the class list can be obtained by
dir(list)
• note: the functions help and dir provide information also about other classes…