PROGRAMMING WITH PYTHON
a.y. 2018-2019
Lesson 11
Decision-making and iterative structures
SEDIN
IT Education Services Center
2
Objectives of the lesson
• Understanding decision-making structures
• Understanding iterative constructs
3
Sequential -vs- decision-making structure
• The order in which program statements are executed hangs on a defined
logical pattern, which is called control structure
• So far we have been using the sequential structure only, that is a set of
statements which are executed in the order they occur
• Sometimes a decision-making structure must be used. In this kind of
structure, a certain action is performed only when specific conditions
happen (same logic of the IF function in Excel)
• In this case we can specify one or more instructions that are executed if a
condition is true (and others if it is false)
4
Sequential structure
Example:
Start
Data
query
Data printing
End
5
Decision-making structures and conditional statements
There are several types of decision-making structures:
• Simple decision-making structure (or conditional execution, or single
alternative)
• Alternative execution (or double alternative)
• Chained conditionals
Decision-making structures are implemented in the code by conditional
statements
In Python the conditional statements are if, else, and elif
6
Simple decision-making structure
Examples of a single alternative decision-making structure:
Is it cold True Is it cold True
outside? outside?
Put on your coat
False Put on your coat False
Put on your hat
Put on your gloves
You can go out !
You can go out !
7
The if statement
In Python, the if statement is used to implement a decision-making structure.
In the case of a single-alternative structure, the syntax will be:
if condition: Heading
statement (if clause)
statement
Body
etc. (indented
statement
[rest of the script] block)
If the condition is false, the statement block is skipped and the program
continues
8
Boolean expressions
• The conditions of the if statement are implemented by means of Boolean
expressions, i.e. expressions that can be true or false
• They use comparison operators (<, > etc.) and return True, whether they
are true, or False
• True and False are special values of bool type, and they must be typed
with a capital letter. They are NOT strings!
9
Comparison operators
The comparison
Operator Description Examples can include values
(integers, floats,
4 == 4 -> True
== Equal to strings etc.),
4 == 73 -> False
variables or
4 != 73 -> True functions.
!= Different from
4 != 4 -> False
73 > 4 -> True Examples:
> Greater than
4 > 73 -> False
a >= 5
73 >= 4 -> True length <= width
>= Greater than or equal to
4 >= 4 -> True
name == 'goofy‘
4 < 73 -> True x >= average(y,z)
< Less than
73 < 4 -> False …
4 <= 73 -> True
<= Less than or equal to
4 <= 4 -> True
10
Example of an if statement
Start
Ask the
value of x
Running the program, it will ask for
the x value and it will behave accordingly:
True
x>0
False Print “x is
positive”
End
11
The if-else statement
• The if-else statement enables to print a double alternative decision-making
structure, which implies two possible execution paths (branches),
depending on whether the condition is true or false
• The general syntax for the if-else statement is as follows:
if condition:
statement Pay attention
statement to colons and
indentation!
Example:
etc.
Improve the following script to show also 'x is negative or 0'
else:
statement
statement
etc.
[rest of the script]
12
Example of if-else statements
Start
Ask the
value of x
Running the program, it will ask for
the x value and it will behave accordingly: False
X>0
True
Print “x is Print “x is
negative or 0” positive”
End
13
Exercise
Set up a program which:
Start
• Requires the user to enter a password (“Enter the
password:”)
Password
request
• Defines whether the entered password is correct, by
comparing it to the one available into the code
(“5ecure”) False Correct True
password
• Prints “Password accepted”, if the password which Print “Sorry, Print “Password
wrong password” accepted”
has been typed is correct
End
• Prints “Sorry, wrong password”, if the password is
not correct
14
Exercise (solution)
Start
Password
request
False Correct True
password
Print “Sorry, Print “Password
wrong password” accepted”
End
15
Nested conditions
• When more difficult situations occur (more conditions, more possible
outputs), it is possible to nest different if-else statements
• In order to verify two conditions (with three possible outputs), the syntax is
the following:
if condition1: Example:
statements Improve the following script to show also 'x is 0' as a
else: separate output
if condition2:
statements
else:
statements
[rest of the script]
16
Example with nested conditions
Start
Ask the
value of x
False True
x>0
False True
Running the program, it x<0
will ask for the x value and
it will behave accordingly:
Print “x is Print “x is
Print “x is 0”
negative” positive”
End
17
Exercise
Set up a program which:
• Requires the user to enter how tall he/she is
(“How tall are you (in cm)?”)
• Requires the user to enter how tall is the person on his/her right
(“How tall is the person on your right (in cm)?”)
• Prints one of the following outputs:
- “You are taller than the person on your right!”
- “You are shorter than the person on your right!”
- “What a coincidence: you are tall exactly like the person on your right!”
18
Exercise (solution)
Start
Ask for alt1
Ask for alt2
Running the program, it will ask for the two heights
and it will respond accordingly: False
alt1 >
True
alt2
False alt2 >
True
alt1
Print “You are as Print “You are Print «You are
tall as…!” shorter than…!” taller than…!»
End
19
The if-elif statement
• In case of chained conditionals (when many cases
and outputs are possible), the elif statement
appears to be a more effective alternative to nested
if-else statements if condition1:
statements
• elif enables to select a statement for each possible
elif condition2:
case
statements
• A chain of elif can be concluded by an else …
elif conditionN:
statement, when there are residual cases, but it is
statements
not compulsory
else:
statements
20
Exercise
We need to write a program that converts an input test score (out of 100) into
an American grade (A-F), as shown in the table below:
Score Grade
91-100 A
81-90 B
71-80 C
61-70 D
0-60 F
After the variables have been assigned and the input score requested, we have
to calculate the A-F grade
21
Exercise (solution)
We can do it by means of a if-else chain, but the resulting code is long and
complex. The solution with if-elif is more effective:
Running the program, it will ask for
the score and it will respond accordingly:
22
Logical operators
They are also called Boolean operators and they enable to create complex
Boolean expressions as well as enhancing conditional constructs potential:
Operator Description
Returns True when all the arguments are
and
true, otherwise it returns False
Returns True when at least one of the
or
arguments is true, otherwise it returns False
Returns True if the argument is false and
not
False when it is true
23
Expressions with logical operators
The expression always produces True or False as a result:
Expression Meaning
Is x greater than y AND is a less than b
x > y and a < b at the same time?
(True or False)
Is x equal to y OR is x equal to z?
x == y or x == z
(True o False)
Is the x > y expression false?
not (x > y)
(True o False)
24
Example of if with logical operators
We have to control the temperature of a refrigerated room, to avoid sub-zero
temperatures for too long
If temp == "Yes" and time >=10:
If temp == "Yes" and time <10:
Residual case (temp == "No", regardless of time value):
25
The if with in statement
• The logical test of the if function can provide a comparison also with a
list of values or with a range
• The keyword in is necessary to use a list of values
Example:
To use a range of values, we need the range function…
26
The range function
• Syntax is: range (start, stop [, step])
• The range function returns an object that produces a sequence of integers
from start (inclusive) to stop (exclusive) by step
range(i, j)
produces: i, i+1, i+2, ..., j-1
• When start is omitted, the default value is 0
range(4)
produces: 0, 1, 2, 3
• When step is given, it specifies the increment (or decrement).
27
Example of if with range
a = 12
if a in range(6,12):
print('The value is OK!')
else:
print('The value is not in the range')
The
…? value is not in the range
>>>
28
Iterative constructs
• Iteration is the ability to execute repeatedly a same block of statements
• It is an essential feature of programming languages, which is implemented
by means of constructs called loops
• Loops are grouped into two categories: loops controlled by a condition and
loops controlled by a counter
• Like many other programming languages, Python’s main iterative
constructs are while and for loops
29
The while loop
while statement enables to create a loop controlled by a condition
The syntax is: «Execute the
statements as
long as the
while condition: condition is
statement true»
statement
statement
... Condition
True
Statement(s)
While clause,
[rest of the script] colon, indented
statement block False
30
Example of while loop
Example: The
variabile
Variations:
must be
initialized 1. Modify the example to print «bye bye!» one
time only, at the end of the list
2. Modify the example to print the same list of
numbers, but in a reversed order (from 10 to 1)
Output: You can 3. Modify the example to print a sequence of numbers based on
also write the inputs given by the user (e.g. all even numbers from 8 to 24)
x+=1
31
Example of while loop (2)
Output:
32
The for loop
for statement enables to create a loop controlled by a counter.
«Execute the
The syntax is: statements for
each variable
value included in
the sequence»
for variable in [value 1, value 2, etc.]: Has every
value of the
True
statement sequence had
its shift?
statement False
statement Assign the
consecutive value
to the variable
... The range
function can also
[rest of the script] be used to show
Execute the
statements
ranges
33
Example of for loop
Example: Variations:
1. Modify the example to use range function
Output: 2. Modify the example to use range(5)
3. Modify the example to show numbers from 5 to 1, using range
34
Example of for loop (2)
Create a program that asks the user to enter an integer number and that print
the multiplication table of that number (i.e all values from n to n*10).
Result:
35
The break and continue statements
• In for and while loops, it might happen that the loop has to be suddenly
interrupted, when specific conditions occur
• At other times, it is necessary to move on to the next loop iteration, when
specific conditions occur
• The break and continue statements respectively are employed for these
two operations:
36
The “Infinite” while loop
A while loop can be executed infinite times, until a specific condition occurs.
In these cases, the while True syntax could also be employed. It requires the if
and break statements, but not the previous initialization of the variable.
Example:
37
The pass statement
• While outlining a program, we might want to temporarily print an if, while
or for construct without any statement, except for a comment
• This happens when we want to test the program or go along with the next
statements, without concluding a certain part
• In these cases we use the pass statement. It acts as a marker for the code
which is going to be completed, avoiding that incomplete constructs return
an error:
38
Tools to learn with today’s lecture
• Conditional constructs: if, if-else, if-elif-else
• Comparison operators, logical operators
• Iterative constructs: while, for
• range function
• pass, break, continue statements
39
Files of the lesson
In the zip file 30424 ITA - 21 - Lesson 11.zip you will find these files:
• 30424 lesson 11 slides.pdf: these slides
• Examples_lesson_11.py: file of the lesson
• Exercises 30424 lesson 11: exercises on the content of the lesson
40
Book references
Learning Python:
Chapters 5, 6
Assignment:
Exercises of lesson 11