0% found this document useful (0 votes)
33 views78 pages

ISOM2007 L3 ControlStructures

This document discusses control structures in Python, including decision structures like if, if-else, and elif statements as well as repetition structures like while and for loops. It provides examples of using if, if-else, and nested if-else statements to make decisions based on conditions. Key topics covered include comparing values, returning different outputs based on conditional logic, and using elif to allow for more than two alternatives in an if-else statement.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views78 pages

ISOM2007 L3 ControlStructures

This document discusses control structures in Python, including decision structures like if, if-else, and elif statements as well as repetition structures like while and for loops. It provides examples of using if, if-else, and nested if-else statements to make decisions based on conditions. Key topics covered include comparing values, returning different outputs based on conditional logic, and using elif to allow for more than two alternatives in an if-else statement.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Lecture 3

Control Structures Of Python


ISOM2007 – 001
Programming for Business Analytics
Learning Goals
2
 In this lecture, you will learn:
 Python Flow Controls
 Decision Structures
 Selection:
 the if, if-else, nested if-else, elif statements
 Repetition:
 the while loop
 the for loop
3
Python Flow Controls
 Python provides standard techniques for
controlling program flows.
 In terms of supporting:
 conditional statements, where different code
blocks are evaluated depending on the value
of a specific condition;
 iterative loop statements that enable repeated
evaluation of a code block until a condition is
met.
Building Block of Program Body
4
Decision Structures: if statement
5

 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

 Example: Input num1


Input num2
num1 = eval (input(“Enter 1st number: “))
num2 = eval (input(“Enter 2nd number: “))
if (num1 > num2): False True
larger = num1 Num1 > num2

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

 Avoid using floating point values to do comparison


 E.g. the following code multiplies the square root of
2 by itself. Ideally, we expect to get the answer 2
r = math.sqrt(2.0)
if r * r == 2.0 :
print("sqrt(2.0) squared is 2.0")
else :
print("sqrt(2.0) squared is not 2.0 but", r * r)

Output:
sqrt(2.0) squared is not 2.0 but 2.0000000000000004
Common Error (number 0)
11

 1 means True and 0 means False


Decision Structures: nested if-else statement
12
 Nested if-else statements
 indented blocks of if-else and if statements can contain
other if-else and if statements
Example:
Example:
exam ==
“yes”
true
false ifif(exam
(exam ==

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

 Examples of loop applications


 Calculating compound interest
 Simulations, event driven programs
 Drawing tiles…
 Compound interest algorithm

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

A loop executes instructions


repeatedly while a condition is True.
01/22/2024
Syntax: while Statement
29

01/22/2024
Count-Controlled Loops
30

 A while loop that is controlled by a counter

counter = 1 # Initialize the counter


while counter <= 10 : # Check the counter
print(counter)
counter = counter + 1 # Update the loop variable

01/22/2024
Event-Controlled Loops
31

 A while loop that is controlled by a counter

balance = INITIAL_BALANCE # Initialize the loop variable


while balance <= TARGET: # Check the loop variable
year – year + 1
balance = balance * 2 # Update the loop variable

01/22/2024
Processing Sentinel Values
32

 Sentinel values are often used:


 When you don’t know how many items are in a list,
use a ‘special’ character or value to signal the “last”
item
 For numeric input of positive numbers, it is common
to use the value -1 salary = 0.0
A sentinel value denotes the while salary >= 0 :
end of a data set, but it is not part salary = float(input())
of the data. if salary >= 0.0 :
total = total + salary
count = count + 1 01/22/2024
Averaging a Set of Values
33

 Declare and initialize a ‘total’ variable to 0


 Declare and initialize a ‘count’ variable to 0
 Declare and initialize a ‘salary’ variable to 0
 Prompt user with instructions
 Loop until sentinel value is entered
 Save entered value to input variable (‘salary’)
 If salary is not -1 or less (sentinel value)
 Add salary variable to total variable
 Add 1 to count variable
 Make sure you have at least one entry before you divide!
 Divide total by count and output.
01/22/2024

 Done!
Sentinel.py (1)
34

Outside the while loop: declare and


initialize variables to use

Since salary is initialized to 0, the while loop


statements will execute at least once

Input new salary and compare to sentinel

Update running total and


count (to calculate the
average later)
01/22/2024
Sentinel.py (2)
35

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

Declare and initialize a variable outside


of the loop to count year

Increment the year variable each time


through

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?

while bal >= TARGET : while bal < TARGET :


year = year + 1 year = year + 1
interest = bal * RATE interest = bal * RATE
bal = bal + interest bal = bal + interest

01/22/2024
Common Error: Infinite Loops
42

 The loop body will execute until the test


condition becomes False.
 What if you forget to update the test
variable?
 bal is the test variable (TARGET doesn’t change)
 You will loop forever! (or until you stop the
program) while bal < TARGET :
year = year + 1
interest = bal * RATE
bal = bal + interest
01/22/2024
Common Error: Off-by-One Errors
43
 A ‘counter’ variable is often used in the test condition
 counter can start at 0 or 1, but programmers often start at 0
 If I want to paint all 5 fingers on one hand, when am I done?
 If you start at 0, use “<“
 0, 1, 2, 3, 4
 If you start at 1, use “<=“
 1, 2, 3, 4, 5
finger = 0 finger = 1
FINGERS = 5 FINGERS = 5
while finger < FINGERS : while finger <= FINGERS :
# paint finger # paint finger
finger = finger + 1 finger = finger + 1
01/22/2024
Hand-Tracing Loops
44

 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

• Start executing loop body statements changing


variable values on a new line
• Cross out values in previous line 01/22/2024
Tracing Sum of Digits
46

• Continue executing loop statements changing variables


• 1729 / 10 leaves 172 (no remainder)
01/22/2024
Tracing Sum of Digits
47

 Test condition. If True, execute loop again


 Variable n is 172, Is 172 > 0?, True!
 Make a new line for the second time
through and update variables

01/22/2024
Tracing Sum of Digits
48

 Third time through


 Variable n is 17 which is still greater than 0
 Execute loop statements and update variables

01/22/2024
Tracing Sum of Digits
49

 Fourth loop iteration:


 Variable n is 1 at start of loop. 1 > 0? True
 Executes loop and changes variable n to 0 (1/10 = 0)

01/22/2024
Tracing Sum of Digits
 Because n is 0, the expression(n > 0) is False
50

 Loop body is not executed


 Jumps to next statement after the loop body
 Finally prints the sum!

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.

You are not qualified,


NEXT! (i.e. continue
with the next one)
58
The while Loop
 Sample Program 6:
 Identify the 1st integer that divisible by 11 from a list of elements
59
The while Loop
 Sample Program 7:
 Count the number of salespersons with sales over $5,000 and determine the
amount of the top sales
60
The while Loop
 Be Caution of the infinite loops, loops that never end.
 Example
Summary of the while Loop
61

 while loops are very common


 Initialize variables before you test
 The condition is tested BEFORE the loop body
 This is called pre-test
 The condition often uses a counter variable
 Something inside the loop should change one
of the variables used in the test
 Watch out for infinite loops! 01/22/2024
The for Loop
62
 The for loop is used to iterate through a sequence of
values.
 The for loop syntax
for var in sequence:
indented block of statements
 where sequence might be an arithmetic progression
of numbers, a string, a list, a tuple, or a file object.
 The variable is successively assigned each value in
the sequence and the indented block of statements is
executed after each assignment.
The for Loop
63
 Uses of a for loop:
 The for loop can be used to iterate over
the contents of any container.
 A container is is an object (Like a string)
that contains or stores a collection of
elements
 A string is a container that stores the
collection of characters in the string 01/22/2024
An Example of a for Loop
64 • important difference:
• In the while loop, the index variable i is assigned 0, 1, and so on.
• In the for loop, the element variable is assigned stateName[0],
stateName[1], and so on.

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

for i in range(1, 10) :


print(i)
for version 01/22/2024
Syntax of a for Statement (Container)
66
 Using a for loop to iterate over the contents
of a container, an element at a time.

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

 Keep the loops simple!

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.

int i = a for i in range(a, b) :


while i < b : . . .
. . .
i = i + 1 01/22/2024
Programming Tip
72

 The loop with symmetric bounds (“<=”, is executed b


- a + 1 times.
 That “+1” is the source of many programming errors.

i = a # For this version of the loop the ‘+1’


while i <= b : is very noticeable!
. . . for year in range(1, numYears + 1) :
i = i + 1

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

 Implement the loop in Python


75
The for Loop
 Looping Through an Arithmetic Progression of
Numbers by using a range function, range (m, n),
which generates the sequence of integers m, m+1,
m+2, . . . , n-1
 Example:
76
The for Loop
 Step Values for the range Function
 Using the range function, range (m, n, s), which generates the
sequence of integers m, m+s, m+2s, . . . , m+rs (where m+rs < n)
 Example:
77
The for Loop
 Looping Through the Characters of a String or Word
for ch in str1
indented block of statements
 Sample Program 1:
 Reverse the order of characters in a given word
78
The for Loop
 Sample Program 2:
 Ask a list of census taken agents for their contributions

You might also like