ISOM2007 L3 ControlStructures
ISOM2007 L3 ControlStructures
if statement syntax
if condition:
indented block of statement(s) when condition is true
execute the block of statement(s)
when the condition is true
do nothing when the condition is false
Decision Structures: if statement
6
Example:
if onlineStudent:
print(“exempt form attendance”) False
onlineStudent
True
Print(“exempt from
attendance”)
Decision Structures: if-else statement
7
if-else statement syntax
if condition:
indented block of statement(s) when condition is true
else:
indented block of statement(s) when condition is false
execute the first block of statement(s) when the condition is
true
execute the second block of statement(s) when the condition
is false.
Decision Structures: if-else statement
8
else:
larger = num2
print(larger) Larger =
num2
Larger =
num1
Print(Larger)
Decision Structures: if-else statement
9
Sample Program:
Input two numbers, compare them and output the
larger number
Common Error (Floating Point)
10
Output:
sqrt(2.0) squared is not 2.0 but 2.0000000000000004
Common Error (number 0)
11
else:
== “yes”):
ifif(score
“yes”):
(score >= 50):
>=
print(“You
50): ✓
print(“YouPassed”)
Passed”)
else:
print(“You
print(“YouFailed”)
Failed”)
false score >= true
50
You You
Example:
Example:
Failed
✘
Passed ifif(exam
(exam == == “yes”):
“yes”):
ifif(score
(score >= 50):
>= 50):
print(“You
print(“YouPassed”)
Passed”)
else:
else:
print(“You
print(“YouFailed”)
Failed”)
Decision Structures: nested if-else statement
13
false true
exam ==
Example:
Example: “yes”
false
ifif(exam
(exam== ==“yes”):
“yes”):
score >=
ifif(score
(score>=>=50):
50):
“non- 50
credit” true
print(“credit-Passed”)
print(“credit-Passed”)
else:
else:
“credit-passed”
print(“Non-credit”)
print(“Non-credit”)
Decision Structures: nested if-else statement
14 Sample Program 1:
capture cost & revenue to determine profit/loss
Decision Structures: nested if-else statement
15
Sample Program 2:
capture scores to determine the letter grade
Decision Structures: elif statement
16
The elif Clause
an extension of the if-else statement
an abbreviation for “else if”.
allows more than two possible alternatives with
the inclusion of elif clauses
Decision Structures: nested if-else statement
17
More on nested if Example:
Example:
statement ififscore
score >=>= 90:90:
grade
grade == “Grade
“GradeA” A”
false
else:
else:
ififscore
score >= >= 80:
80:
false grade
grade == “Grade
“Grade B” B”
true else:
else:
false ififscore
score >= >= 70:
70:
true grade
grade == “Grade
“Grade C”C”
false else:
else:
true ififscore
score >=>= 60:
60:
true grade
grade == “Grade
“Grade D”
D”
else:
else:
false true ififscore
score >=
>= 50:
50:
grade
grade == “Grade
“Grade E”
E”
else:
else:
grade
grade == “Grade
“Grade F”
F”
Decision Structures: nested if-else statement
18
Sample Program:
Determine the letter grade for an input score
Decision Structures: elif statement
19
Substitute the nested if-else with the elif
Example:
Example:
true Grade A ifif score
score >=
>= 90:
90:
false print
print (”You
(”You got
got an
anAA\n")
\n")
true Grade B
false elif
elif score
score >=
>= 80:
80:
print
print (“You
(“You got
got aa BB \n”)
\n”)
true Grade C
false elif
elif score
score >=
>= 70:
70:
true Grade D
print
print (“You got
(“You got aa CC \n”)
\n”)
false
elif
elif score
score >=
>= 60:
60:
true Grade E print
print (“You
(“You got
got aa D
D \n”)
\n”)
false
Grade F
elif
elif score
score >=
>= 50:
50:
print
print (“You
(“You got
got aa EE \n”)
\n”)
else:
else:
print
print (“You
(“You got
got aa FF \n”)
\n”)
Decision Structures: elif statement
20 Sample Program:
using the elif statement instead of the if statement
if, elif (Multiway Branching)
21
if richter >= 8.0 : # Handle the ‘special case’ first
print("Most structures fall")
elif richter >= 7.0 :
print("Many buildings destroyed")
elif richter >= 6.0 :
print("Many buildings damaged, some collapsed")
elif richter >= 4.5 :
print("Damage to poorly constructed buildings")
else : # so that the ‘general case’ can be handled last
print("No destruction of buildings")
What is Wrong With This Code?
22
if richter >= 8.0 :
print("Most structures fall")
if richter >= 7.0 :
print("Many buildings destroyed")
if richter >= 6.0 :
print("Many buildings damaged, some collapsed")
if richter >= 4.5 :
print("Damage to poorly constructed buildings")
Decision Structures: nested if-else statements
23 The Importance of Indentation – Python use the indentation to determine the scope of
logic or your program’s logical structures.
What happens if 88 is the input?
Decision Structures: nested if-else statements
24
The Important of Indentation – Python use the indentation to determine the scope of
logic or your program’s logical structures.
The while Loop
25
The while loop repeatedly executes an indented block of
statements as long as a certain condition is met.
A while loop syntax
while condition:
indented block of statements when condition is still
true
If the condition is False, Python skips over the body of the
loop.
If the condition is True, the body of the loop will be
executed.
The body will be continually executed until the
continuation condition evaluates to False.
26
The while Loop
Example
num = 1
while num <= 5:
print(num)
num += 1 # increase num by 1
The while Loop
27
Steps
01/22/2024
Planning the while Loop
28
balance = 10.0
target = 100.0
year = 0
rate = 0.025
while balance < TARGET :
year = year + 1
interest = balance * RATE/100
balance = balance + interest
01/22/2024
Count-Controlled Loops
30
01/22/2024
Event-Controlled Loops
31
01/22/2024
Processing Sentinel Values
32
Done!
Sentinel.py (1)
34
Prevent divide by 0
Calculate and
output the average
salary using the
total and count
variables
01/22/2024
Execution of the while Loop
36
01/22/2024
Execution of the while Loop
37
01/22/2024
Doubleinv.py
38
01/22/2024
while Loop Examples
39
01/22/2024
while Loop Examples (2)
40
01/22/2024
Common Error: Incorrect Test Condition
41
The loop body will only execute if the test condition is True.
If bal is initialized as less than the TARGET and should grow
until it reaches TARGET
Which version will execute the loop body?
01/22/2024
Common Error: Infinite Loops
42
Example:
Calculate the sum of digits (1+7+2+9)
Make columns for key variables (n, total, digit)
Examine the code and number the steps
Set variables to state before loop begins
01/22/2024
Tracing Sum of Digits
45
01/22/2024
Tracing Sum of Digits
48
01/22/2024
Tracing Sum of Digits
49
01/22/2024
Tracing Sum of Digits
Because n is 0, the expression(n > 0) is False
50
01/22/2024
51
The while Loop
Sample Program 1:
Identify the max, min and average of a sequence of numbers
52
The while Loop
Sample Program 2:
Factorize a non-zero positive integer
53
The while Loop
The break statement in the while loop
causes an exit from anywhere in the body of a loop
while condition:
indented body of the while statement before the if testing
Sorry, closed! Off!
if some-condition: 收工 !!!!
(i.e. terminate the while
break statement)
indented body of the while statement after the if testing
54
The while Loop
Sample Program 3:
Obtain a list of numbers
The while Loop
55
Sample Program 4:
Identify the max, min
and average of a
sequence of input
numbers – an alternate
approach
56
The while Loop
Sample Program 5:
Input a number of transactions and calculate their profits
The while Loop
57
The continue statement in the while loop
When the statement continue is executed in the body of a while loop, the current
instance of the loop terminates and the execution returns to the loop’s header
(warning, you still need to have your termination criteria to avoid the infinitive
looping).
continue statements usually appear inside if statements.
stateName = "Virginia"
i = 0
while i < len(stateName) :
letter = stateName[i]
print(letter) while version
i = i + 1
stateName = "Virginia"
for letter in stateName :
print(letter) 01/22/2024
for version
The for Loop (2)
65
Uses of a for loop:
A for loop can also be used as a count-
controlled loop that iterates over a range
of integer values.
i = 1
while i < 10 :
print(i) while version
i = i + 1
01/22/2024
Syntax of a for Statement (Range)
67
You can use a for loop as a count-controlled loop to iterate over a range of
integer values
We use the range function for generating a sequence of integers that less than
the argument that can be used with the for loop
01/22/2024
Planning a for Loop
68
Print the balance at the end of
each year for a number of years
01/22/2024
Good Examples of for Loops
69
01/22/2024
Investment Example
70
01/22/2024
Programming Tip
71
Finding the correct lower and upper bounds for a loop can be
confusing.
Should you start at 0 or at 1?
Should you use <= b or < b as a termination condition?
Counting is easier for loops with asymmetric bounds.
The following loops are executed b - a times.
01/22/2024
Summary of the for Loop
73
for loops are very powerful
The for loop can be used to iterate over the
contents of any container, which is an object
that contains or stores a collection of elements
a string is a container that stores the collection of
characters in the string.
A for loop can also be used as a count-
controlled loop that iterates over a range of
integer values. 01/22/2024
Steps to Writing a Loop
74
Planning:
Decide what work to do inside the loop
Specify the loop condition
Determine loop type
Setup variables before the first loop
Process results when the loop is finished
Trace the loop with typical examples
Coding: 01/22/2024