Lec03 Control Flow
Lec03 Control Flow
Computer
Principles and
Python
Programming
Lecture 3: Control Flow
2024-25 Term 2
By Dr. King Tin Lam
Outline
• Conditional Statements
• if
• elif
• else
• Looping Statements
• while
• for
• break
• continue
2
Boolean expressions
• A boolean expression is an expression that is either true or false.
• For example,
>>> 1 == 1
True
>>> 2 == 3
False
• True and False are special values that belong to the class bool; they
are not strings, and are stored internally as 1 and 0:
>>> type(True) >>> int(True)
<class 'bool'> 1
>>> type(False) >>> int(False)
<class 'bool'> 0
3
Recap of Comparison Operators
x == y # x is equal to y
x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y
• Reminder:
• A common error is to use = (assignment operator) instead of == for comparison.
• There is no such thing as =< or =>.
4
Conditional Statements
Conditionals - Decision Points
5
Conditional Statements
• To write useful programs, we almost always need the ability to check
conditions and change the behavior of the program accordingly.
• Conditional or branching statements give us this ability.
• Constructs:
• if
• elif
• else
• x if condition else y (a "ternary operator" in Python)
• match ... case ... (since Python 3.10)
• Python does not have a "switch" statement. This construct can be used like a switch.
6
if Statements
• The simplest form of conditionals is the if statement.
<boolean
false
expression>
Syntax:
if <boolean expression> : true
<statement A>
... <statement>
• Example: if x % 2 == 0:
print('x is even')
else:
print('x is odd') 10
Chained Conditionals
• Sometimes there are more than two possibilities, and we need more
than two branches.
• One way to express a computation like that is a chained conditional:
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
13
Nested if Statements
• e.g., Pay a certain tax rate depending on income level.
income = 48000
Income Rate rate = 0.0
0 - 47,450 22%
if income < 47450:
47,450 – 114,650 25% rate = 0.22 5 mutually exclusive
114,650 – 174,700 28% elif income < 114650: alternatives
rate = 0.25
174,700 – 311,950 33% elif income < 174700:
>>> rate
311,950 - 35% rate = 0.28
0.25
elif income < 311950:
rate = 0.33
else:
rate = 0.35
14
Nested if Statements But nested if-else looks more complex.
We generally avoid it whenever possible.
15
Nested if Statements
• Q. What's wrong with the following for income tax calculation?
Income Rate income = 48000 Logical bug: each if statement undoes
rate = 0.35 the previous one. The code is
0 - 47,450 22%
if income < 47450: equivalent to
47,450 – 114,650 25% rate = 0.22
114,650 – 174,700 28% if income < 114650: if income < 311950:
rate = 0.25 rate = 0.33
174,700 – 311,950 33%
if income < 174700: else:
311,950 - 35% rate = 0.28 rate = 0.35
if income < 311950:
rate = 0.33 So, note when you need if-else
(mutually exclusive) or just if
>>> rate (probably overlapping).
0.33
16
Short-Circuiting
• What is the result of executing the following code?
>>> num = 3
>>> denom = 0
>>> quot = num / denom
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
17
Short-Circuiting
• What is the result of executing the following code?
• A) Here B) There C) Runtime error
The answer is B.
num = 3 Explanation
denom = 0 There is no runtime error.
if denom != 0 and num / denom > 10: The division of num/denom will not
print("here") be carried out at all.
else: This is because the first condition
print("there") (denom != 0) has been evaluated to
false. So no matter whether the latter
condition gets to be true or false, the
whole condition will be false, and the
control will fall into the ‘else’ case.
18
Short-Circuiting
• The or operator results in True when the first operand is True, no
matter what the second operand is.
• The and operator results in False when the first operand is False, no
matter what the second operand is.
• Python will not evaluate the right-hand operand when the outcome
can be determined by the left operand alone.
• This skipping in the evaluation is called short-circuiting.
• So, can you tell the result of the following in two seconds?
>>> a = 1; b = 324; c = 223
>>> print(a == 1 or b * 6547 > c * 8675)
True 19
Revisit of Boolean Expressions
In reality, we won’t write conditions like this.
• How about this one? But do you know the evaluation result?
22
Conditional Expressions
• C/C++/Java has the conditional operator ? : which is a short form of if-
else logic used in an expression. It is also called the ternary operator
because it has three operands.
• Syntax: condition ? value_if_true : value_if_false
if condition:
which is equivalent to: var = true_value
else:
var = false_value
• Example:
a, b = 10, 20
if a < b:
a, b = 10, 20 min = a
min = a if a < b else b else :
print(min) # output 10 min = b
print(min) # output 10
24
Looping Statements
Repeating tasks is the common situation that requires programming.
25
Constructs for Looping
• while
• for
• range()
• break
• continue
26
Why Looping (or Iteration)?
• Computers are often used to automate repetitive tasks.
• Repeating identical or similar tasks without making errors is
something that computers do much better than humans do.
• Python provides two main ways to do this:
• while statement
• for statement
27
The while Statement
• The while statement lets you execute a statement (block) repeatedly
as far as a condition is satisfied.
• Syntax: while test-condition:
# loop body
statement(s) <boolean
false
Output: expression>
• Example: n=5 5
true
while n > 0: 4
print(n) 3
<statement>
n=n-1 2
1
print('Blastoff!') Blastoff!
1 2 true
N = 6
29
Infinite Loops
• Try this slightly modified program. What do you observe?
• Beware of your indentation!
N=6
i=0
v=1
while i <= N:
print(i, ":", v)
v=2*v
i=i+1
30
Exercise: while loop
• What is the output of the following code?
before image: after image:
iteration a b b < 10 printed a b
a, b = 0, 1 1
while b < 10: 1 1 0 1 True 1 1 0+1=1
print(b) 2 2 1 1 True 1 1 1+1=2
a, b = b, a+b 3
5 3 1 2 True 2 2 1+2=3
print('Done!') 8 4 2 3 True 3 3 2+3=5
Done!
5 3 5 True 5 5 3+5=8
6 5 8 True 8 8 5+8=13
7 8 13 False
31
The break Statement
• We can add code to the body of the loop to explicitly exit the loop
using the break statement when we have reached the exit condition.
• For example, suppose you want to take input from the user until they
type "done". You could write:
if I put the line = input('> ') in the first while True: > hello there
line, it will... line = input('> ') define the "line" hello there
if line == 'done': > finished
break finished
the same
print(line) > done
Done!
print('Done!')
32
FYI, Python doesn't support
"labeled break" as in Java. No loop
The break Statement labeling and jumping to a label.
print('Done!')
34
The do … while Loop
• At times, we face situations that require us to use the do-while loop,
which is a post-test loop (it checks the condition only after executing
the loop body, at least once).
• Python does not explicitly have the do-while loop. But we can
emulate it using the break statement.
• This example loop executes at least once to accept the user's input.
while True: > hello there
line = input('> ') hello there
if line == 'done': > finished
break finished
print(line) > done
Done!
print('Done!')
35
The while … else Construct
• Python supports having an else statement associated with a loop
statement.
• With a for loop, the else statement is executed when the loop has exhausted
iterating the list.
• With a while loop, the else statement is executed when the condition
becomes false.
• Example:
count = 0
0 is less than 5 while count < 5:
1 is less than 5 print(count, " is less than 5")
2 is less than 5 count = count + 1
3 is less than 5 else:
4 is less than 5 print(count, " is not less than 5")
5 is not less than 5
36
The while … else Construct
• What's the point of having the else clause? It seems writing the else
body as standalone statements also works.
37
The while … else Construct
• For example, let's say we have a piece of code like this:
csci1550 = [ "Noah", "Daniel", "Sean" ]
student = input('Enter a name: ')
index = 0
found = False Enter a name: Sean
while index < len(csci1550): Sean is found!
if csci1550[index] == student:
found = True Enter a name: Jason
print(student, "is found!") ['Noah', 'Daniel', 'Sean', 'Jason']
break
index += 1
if not found:
csci1550.append(student)
print(csci1550)
38
The while … else Construct
• The code becomes more concise when using while ... else instead.
csci1550 = [ "Noah", "Daniel", "Sean" ]
student = input('Enter a name: ')
39
The for Statement
• Sometimes we want to loop through a set of things such as a list of
words, the lines in a file, or a list of numbers. In this case, we can
construct a definite loop using a for statement.
• We call the while statement an indefinite loop because it loops until
some condition becomes false.
friends = ['Noah', 'Daniel', 'Sean', 'Jason']
for friend in friends:
print('Happy Lunar New Year to', friend)
41
The for Statement
• Let's try the following code. What's getting printed?
friends = ['Noah', 'Daniel', 'Sean', 'Jason’]
for friend in friends:
friend = 'forever'
print(friends)
• Assigning the iteration variable doesn't affect the original list items.
iteration variable -> friend (friends Xÿ
)
42
The range() Function
• There is a built-in function in Python called range(), which is used to
generate a list of integers. The range function has one, two or three
parameters.
• The general form of the range function is:
range(stop)
• start is the first number in the sequence; stop is the exclusive limit by
which the sequence stops.
• step is the difference between each pair of numbers in the sequence.
43
The range() Function
• Create a list of integers from 1 to 5.
>>> list(range(1, 6))
[1, 2, 3, 4, 5]
• Note: the stop value, i.e., 6 here, is excluded from the list.
• By default, the difference (step) between two successive numbers is 1.
• Create a list of integers from 1 to 20 with a difference of 2 between
two successive integers.
list(range(1, 20, 2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
44
stop
The range() Function Short-form:
>>> range(5)
range(0, 5)
• Syntax: range(start, stop[, step]) >>> list(range(5))
[0, 1, 2, 3, 4]
• Examples:
For +ve step, the contents of a range r are
range(5, 10) range(12, 6) given by r[i] = start + step*i
5, 6, 7, 8, 9 <empty> where i >= 0 and r[i] < stop.
46
Range-based for Loop
• The range() function allows us to make some counter-based loops.
• Example: for x in range(0, 5): x=0
print("x = %d" % (x)) x=1
x=2
x=3
x=4
• Alternative syntax:
for var in list(range(5)): 0
print(var) 1
2
3
>>> list(range(5)) 4
[0, 1, 2, 3, 4]
47
Range-based for Loop
• What will this code print?
0 0
for i in range(10): 5 1
print(i) 6 2
i=5 7 3
8 4
9 5
• The i = 5 statement will not affect the for-loop because 6
7
i will be overwritten with the next index in the range. 8
9
The for-loop makes assignments to the variables in the target list. This
overwrites all previous assignments to those variables including those
made in the suite of the for-loop
https://docs.python.org/3/reference/compound_stmts.html#for
48
Range-based for Loop
• Using the range() and len() functions, we can iterate over elements in
an iterable (e.g., a list) through their indexes.
• This way, we can modify the elements. For example,
lyrics = ['Mary', 'had', 'a', 'little', 'lamb']
for i in (range(len(lyrics))):
print(i, lyrics[i])
lyrics[i] = lyrics[i].swapcase()
print(lyrics)
0 Mary
1 had
2a
3 little
4 lamb
['mARY', 'HAD', 'A', 'LITTLE', 'LAMB']
49
The enumerate() function
• The enumerate() function assigns an index to each item in an iterable
object, making it easier to keep track of the content of the iterable.
• Examples of iterables: lists, tuples, strings, or any sequence that can be
iterated over in a for-loop
start is an optional parameter
• Syntax: enumerate(iterable, start=0) that tells the function which
index to use for the first item
• Example: of the iterable.
>>> cars = ['kia', 'audi', 'bmw']
>>> type(enumerate(cars))
<class 'enumerate'>
>>> print(list(enumerate(cars)))
[(0, 'kia'), (1, 'audi'), (2, 'bmw')]
>>> print(list(enumerate(cars, start=1)))
[(1, 'kia'), (2, 'audi'), (3, 'bmw')]
50
The enumerate() function
• Using enumerate() in a for-loop:
iteration 1: Noah
friends = ['Noah', 'Daniel', 'Sean', 'Jason']
iteration 2: Daniel
for i, name in enumerate(friends, start=1):
iteration 3: Sean
print(f"iteration {i}: {name}")
iteration 4: Jason
52