4/17/2023
Application Programming
with Python
Lecturer: Nguyen Van Hong
Control structure
in python
1
4/17/2023
2
4/17/2023
3
4/17/2023
4
4/17/2023
CONDITIONAL CONSTRUCT – if else STATEMENT
False
Condition ? Statement 1 Statement 2
True
Statement 1
else
Statement 2 body
Main
Body
10
10
5
4/17/2023
11
12
6
4/17/2023
13
13
while loop
n=5 Repeated Steps
Output:
No Yes Program:
n>0? 5
n = 5 4
print(n) while n > 0 :
3
print(n)
n = n – 1 2
n = n -1 print('Blastoff!') 1
print(n) Blastoff!
0
Loops (repeated steps) have iteration variables that
print('Blastoff') change each time through a loop. Often these iteration
variables go through a sequence of numbers.
14
7
4/17/2023
n=5 An Infinite Loop
No Yes
n>0?
n = 5
while n > 0 :
print('Lather') print('Lather')
print('Rinse')
print('Rinse') print('Dry off!')
What is wrong with this loop?
print('Dry off!')
15
n=0 Another Loop
No Yes
n>0?
n = 0
print('Lather') while n > 0 :
print('Lather')
print('Rinse') print('Rinse')
print('Dry off!')
print('Dry off!') What is this loop doing?
16
8
4/17/2023
Breaking Out of a Loop
The break statement ends the current loop and jumps to the
statement immediately following the loop
It is like a loop test that can happen anywhere in the body of the
loop
while True:
> hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
17
Breaking Out of a Loop
The break statement ends the current loop and jumps to the
statement immediately following the loop
It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
18
9
4/17/2023
while True: No Yes
line = input('> ') True ?
if line == 'done' :
break ....
print(line)
print('Done!') break
...
print('Done')
19
Finishing an Iteration with continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
hello there
if line[0] == '#' :
> # don't print this
continue
> print this!
if line == 'done' :
print this!
break
> done
print(line)
Done!
print('Done!')
20
10
4/17/2023
Finishing an Iteration with continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
line = input('> ') > hello there
if line[0] == '#' : hello there
> # don't print this
continue
> print this!
if line == 'done' : print this!
break > done
print(line) Done!
print('Done!')
21
No
True ? Yes
while True:
line = input('> ')
....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print(line) ...
print('Done!')
print('Done')
22
11
4/17/2023
Indefinite Loops
• While loops are called “indefinite loops” because they keep going
until a logical condition becomes False
• The loops we have seen so far are pretty easy to examine to see if
they will terminate or if they will be “infinite loops”
• Sometimes it is a little harder to be sure if a loop will terminate
23
Definite Loops
Iterating over a set of items…
24
12
4/17/2023
Definite Loops
Quite often we have a list of items of the lines in a file -
effectively a finite set of things
We can write a loop to run the loop once for each of the items
in a set using the Python for construct
These loops are called “definite loops” because they execute
an exact number of times
We say that “definite loops iterate through the members of a
set”
25
A Simple Definite Loop
5
4
for i in [5, 4, 3, 2, 1] :
3
print(i)
print('Blastoff!') 2
1
Blastoff!
26
13
4/17/2023
A Definite Loop with Strings
Happy New Year: Joseph
friends = ['Joseph', 'Glenn', 'Sally']
Happy New Year: Glenn
for friend in friends :
print('Happy New Year:', friend) Happy New Year: Sally
print('Done!')
Done!
27
A Simple Definite Loop
Yes No 5
Done? Move i ahead for i in [5, 4, 3, 2, 1]: 4
3
print(i) 2
print(i) print('Blastoff!') 1
Blastoff!
Definite loops (for loops) have explicit iteration variables
print('Blast off!') that change each time through a loop. These iteration
variables move through the sequence or set.
28
14
4/17/2023
Looking at in...
The iteration variable
“iterates” through the Five-element
sequence (ordered set) sequence
Iteration variable
The block (body) of code is
executed once for each value for i in [5, 4, 3, 2, 1] :
in the sequence print(i)
The iteration variable moves
through all of the values in the
sequence
29
No The iteration variable “iterates”
Yes
Done? Move i ahead through the sequence (ordered
set)
print(i)
The block (body) of code is
executed once for each value
in the sequence
The iteration variable moves
for i in [5, 4, 3, 2, 1]: through all of the values in the
print(i) sequence
30
15
4/17/2023
i=5
No print(i)
Yes
Done? Move i ahead i=4
print(i)
print(i)
i=3
print(i)
i=2
for i in [5, 4, 3, 2, 1] : print(i)
print(i) i=1
print(i)
31
Loop Idioms:
What We Do in Loops
Note: Even though these examples are simple,
the patterns apply to all kinds of loops
32
16
4/17/2023
Making “smart” loops
Set some variables to
initial values
for thing in data:
The trick is “knowing” something
Look for something or do
about the whole loop when you
something to each entry
are stuck writing code that only
separately, updating a
sees one entry at a time variable
Look at the variables
33
Looping Through a Set
$ python basicloop.py
Before
print('Before') 9
41
for thing in [9, 41, 12, 3, 74, 15]:
12
print(thing)
3
print('After')
74
15
After
34
17
4/17/2023
What is the Largest Number?
35
What is the Largest Number?
36
18
4/17/2023
What is the Largest Number?
41
37
What is the Largest Number?
12
38
19
4/17/2023
What is the Largest Number?
39
What is the Largest Number?
74
40
20
4/17/2023
What is the Largest Number?
15
41
What is the Largest Number?
42
21
4/17/2023
What is the Largest Number?
3 41 12 9 74 15
43
What is the Largest Number?
largest_so_far -1
44
22
4/17/2023
What is the Largest Number?
largest_so_far 3
45
What is the Largest Number?
41
largest_so_far 41
46
23
4/17/2023
What is the Largest Number?
12
largest_so_far 41
47
What is the Largest Number?
largest_so_far 41
48
24
4/17/2023
What is the Largest Number?
74
largest_so_far 74
49
What is the Largest Number?
15
74
50
25
4/17/2023
What is the Largest Number?
3 41 12 9 74 15
74
51
Finding the Largest Value
largest_so_far = -1 $ python largest.py
print('Before', largest_so_far) Before -1
9 9
for the_num in [9, 41, 12, 3, 74, 15]:
41 41
if the_num > largest_so_far :
41 12
largest_so_far = the_num 41 3
print(largest_so_far, the_num) 74 74
74 15
print('After', largest_so_far) After 74
We make a variable that contains the largest value we have seen so far. If the current
number we are looking at is larger, it is the new largest value we have seen so far.
52
26
4/17/2023
More Loop Patterns…
53
Counting in a Loop
zork = 0
print('Before', zork)
$ python
for thing in [9, 41, 12, 3, 74, 15] : countloop.py
zork = zork + 1 Before 0
print(zork, thing)
print('After', zork)
19
2 41
To count how many times we execute a loop, we 3 12
introduce a counter variable that starts at 0 and we add 43
one to it each time through the loop. 5 74
6 15
After 6
54
27
4/17/2023
Summing in a Loop
zork = 0 $ python
print('Before', zork) countloop.py
for thing in [9, 41, 12, 3, 74, 15]: Before 0
zork = zork + thing 99
print(zork, thing) 50 41
print('After', zork) 62 12
65 3
To add up a value we encounter in a loop, we introduce 139 74
a sum variable that starts at 0 and we add the value to the 154 15
sum each time through the loop. After 154
55
Finding the Average in a Loop
count = 0
sum = 0 $ python
print('Before', count, sum) averageloop.py
for value in [9, 41, 12, 3, 74, 15]: Before 0 0
count = count + 1 199
sum = sum + value 2 50 41
print(count, sum, value) 3 62 12
print('After', count, sum, sum/count) 4 65 3
5 139 74
An average just combines the counting and sum 6 154 15
patterns and divides when the loop is done. After 6 154 25.666
56
28
4/17/2023
Filtering in a Loop
print('Before') $ python search1.py
for value in [9, 41, 12, 3, 74, 15] : Before
if value > 20: Large number 41
print('Large number',value) Large number 74
After
print('After')
We use an if statement in the loop to catch / filter the values we are
looking for.
57
Search Using a Boolean Variable
found = False $ python search1.py
Before False
print('Before', found) False 9
for value in [9, 41, 12, 3, 74, 15] : False 41
if value == 3 : False 12
found = True True 3
True 74
print(found, value)
True 15
print('After', found) After True
If we just want to search and know if a value was found, we use a variable that starts
at False and is set to True as soon as we find what we are looking for.
58
29
4/17/2023
How to Find the Smallest Value
$ python largest.py
largest_so_far = -1
Before -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : 9 9
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
How would we change this to make it find the smallest value in the list?
59
Finding the Smallest Value
smallest_so_far = -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far, the_num)
print('After', smallest_so_far)
We switched the variable name to smallest_so_far and switched the > to <
60
30
4/17/2023
Finding the Smallest Value
$ python smallbad.py
smallest_so_far = -1
Before -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : -1 9
if the_num < smallest_so_far : -1 41
smallest_so_far = the_num -1 12
print(smallest_so_far, the_num) -1 3
-1 74
print('After', smallest_so_far) -1 15
After -1
We switched the variable name to smallest_so_far and switched the > to <
61
Finding the Smallest Value
smallest = None $ python smallest.py
print('Before') Before
for value in [9, 41, 12, 3, 74, 15]: 99
if smallest is None : 9 41
smallest = value 9 12
elif value < smallest : 33
smallest = value 3 74
print(smallest, value) 3 15
print('After', smallest) After 3
We still have a variable that is the smallest so far. The first time through
the loop smallest is None, so we take the first value to be the smallest.
62
31
4/17/2023
The is and is not Operators
Python has an is
smallest = None operator that can be
print('Before') used in logical
for value in [3, 41, 12, 9, 74, 15] : expressions
if smallest is None :
smallest = value Implies “is the same as”
elif value < smallest :
smallest = value Similar to, but stronger
print(smallest, value)
than ==
print('After', smallest)
is not also is a logical
operator
63
Summary
• While loops (indefinite) • For loops (definite)
• Infinite loops • Iteration variables
• Using break • Loop idioms
• Using continue • Largest or smallest
• None constants and variables
64
32
4/17/2023
Function Description
int(x [,base]) Data Type Conversion:
Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
65
Acknowledgements / Contributions
Initial Development: Charles Severance, University of Michigan School of Information
Update and modify Nguyen Van Hong, HUST
66
33