0% found this document useful (0 votes)
2 views52 pages

Lec03 Control Flow

The document outlines control flow in Python programming, focusing on conditional statements (if, elif, else) and looping constructs (while, for). It explains boolean expressions, comparison operators, and the use of short-circuiting in logical operations. Additionally, it covers nested conditionals and provides examples of how to implement these concepts in Python code.

Uploaded by

jialinli865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views52 pages

Lec03 Control Flow

The document outlines control flow in Python programming, focusing on conditional statements (if, elif, else) and looping constructs (while, for). It explains boolean expressions, comparison operators, and the use of short-circuiting in logical operations. Additionally, it covers nested conditionals and provides examples of how to implement these concepts in Python code.

Uploaded by

jialinli865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

CSCI1550

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>

• The boolean expression after the if statement is called the condition.


We end the if statement with a colon (:) and the line(s) after the if
statement are indented.
• Example: x = int(input("Enter x: "))
if x > 0:
print('x is positive')
7
if Statements
• All lines indented under the if .. : line are the body of the if statement.
if x > 0:
print('x is positive')
x=x+1

• There is no limit on the number of statements that can appear in the


body, but there must be at least one.
• Occasionally, it is useful to have a body with no statements (usually as a place
holder for code you haven’t written yet). In that case, you can use the pass
statement, which does nothing.
if x < 0 :
pass # need to handle negative values!
8
if Statements
• When using the Python interpreter (interactive mode), you must
leave a blank line at the end of a block, otherwise Python will return
an error:
>>> x = 3
>>> if x < 10:
... print('Small')
... print('Done')
File "<stdin>", line 3
print('Done')
^
SyntaxError: invalid syntax

• A blank line at the end of a block of statements is not necessary when


writing and executing a script, but it may improve code readability.
9
The if .. else Statement
• if .. else allows you execute a statement (block) when a condition is
satisfied or another statement (block) when otherwise.
Syntax:
true false
if <boolean expression> : <boolean
expression>
<statement A>
...
else: <statement A> <statement B>
<statement B>
...

• 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')

• Keyword elif is an abbreviation of "else if",


and exactly one branch will be executed.
11
Chained Conditionals
• There is no limit on the number of elif statements. If there is an else
clause, it has to be at the end, but there doesn’t have to be one.
if choice == 'a':
print('Bad guess')
elif choice == 'b':
print('Good guess')
elif choice == 'c':
print('Close, but not correct')

• Each condition is checked in order. If the first is false, the next is


checked, and so on. If one of them is true, the corresponding branch
executes, and the statement ends. Even if more than one condition is
true, only the first true branch executes.
12
Look inside only
after you can
Nested Conditionals open the
outermost box.

• One conditional can also be nested within another.


• We could have written the three-branch example like this:

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.

• We may also use nested if statements to handle multiple alternatives.


if income < 47450: if income < 47450:
rate = 0.22 rate = 0.22
elif income < 114650: else:
rate = 0.25 if income < 114650:
elif income < 174700: equivalent rate = 0.25
rate = 0.28 else:
elif income < 311950: if income < 174700:
rate = 0.33 rate = 0.28
else: else:
rate = 0.35 if income < 311950:
rate = 0.33
else:
rate = 0.35

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?

if 0.01 and 0.02:


print("Yes, it's true!") >>> bool(0.01)
else: True
print("No, it's false!") >>> bool(0.02)
True
Yes, it's true! >>> bool(10)
True
>>> bool(-1)
• Strictly speaking, the operands of the logical operators True
should be boolean expressions, but Python is not very >>> bool(-0.00001)
True
strict. Any nonzero number is interpreted as True. >>> bool(0)
False
>>> bool(0.0)
bool("") False False
bool(" ") True
bool([]) False 20
Again, we won’t write
conditions like these.
Revisit of Boolean Expressions But do you know each
evaluation result?

• What are the evaluation results of the following expressions?


>>> 5 and 6
6
>>> 0.0 and 2.34
0.0
>>> "positive" or "negative"
'positive'
>>> not "positive" or "negative"
not "positive" -> not truthy -> false
'negative'
>>> not '-ve' or not '+ve'
False
>>> not 0 and 1 1 or "positive"
1
1 1 and "positive"
>>> not 0 or 1 positive
True
21
Revisit of Boolean Expressions
• From the Python documentation: The expression x and y first
evaluates x; if x is false, its value is returned; otherwise, y is
evaluated, and the resulting value is returned.
x and y Returns x if x is False, y otherwise
x or y Returns y if x is False, x otherwise
not x Returns False if x is True, True otherwise

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

int x = 10, y = 20, max;


if (x > y)
int x = 10, y = 20;
max = x;
int max = (x > y) ? x : y;
else
max = y;
condition
expression if true
expression if false
23
Conditional Expressions
• In Python, there is a conditional expression construct similar to the
ternary operator in C.
• Syntax: var = true_value if condition else false_value

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

• Python does not have a do-while loop construct.

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!

• We call each time we execute the body of the loop an iteration.


28
While Loop Example: Powers of Two
• Print powers of 2 that are  2N.
• Increment i from 0 to N. i v i <= N

• Double v each time. 0 1 true

1 2 true

N=6 0:1 2 4 true


i=0 1:2
3 8 true
v=1 2:4
while i <= N: 3:8 4 16 true
4 : 16
print(i, ":", v) 5 32 true
5 : 32
v=2*v 6 : 64 6 64 true
i=i+1
7 128 false

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.

• Like in C, the break statement breaks out of the innermost


enclosing for or while loop.
• Compare code snippets below. If you want to break out of the outer
loop as well, you need another break.
n=1 n=1
while n <= 10: The outer loop runs as long as n is less than or equal to 10. while n <= 10:
while n > 3: The inner loop runs only if n is greater than 3. while n > 3:
print("n =", n) n=4 print("n =", n)
break n=5 break
n=6 n=4
n += 1 n=7 n += 1 n=5
n=8 if (n > 6): n=6
n=9 break
n = 10
33
The continue Statement
• Sometimes you are in an iteration of a loop and want to finish the
current iteration and immediately jump to the next iteration.
• You can use the continue statement to skip to the next iteration
without finishing the body of the loop for the current 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!')
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.

• The else clause is executed only when the while condition


becomes false. If you break out of the loop, or if an exception is
raised, it won't be executed.

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: ')

index = 0 Enter a name: Sean


while index < len(csci1550): Sean is found!
if csci1550[index] == student:
print(student, "is found!") Enter a name: Jason
break ['Noah', 'Daniel', 'Sean', 'Jason']
index += 1
else:
csci1550.append(student)
print(csci1550)

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)

print('Done!') Happy Lunar New Year to Noah


Happy Lunar New Year to Daniel
Happy Lunar New Year to Sean
Happy Lunar New Year to Jason
Done! 40
The for Statement
• In the last example, the variable friend is called the iteration
variable for the loop. It changes for each iteration of the loop and
controls when the for loop completes. It steps successively through
the strings stored in the friends list.
• The number of iteration is definite and equal to the number of items
in the list (or other collective structures).

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)

['forever', 'forever', 'forever', 'forever']

['Noah', 'Daniel', 'Sean', 'Jason']

• 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)

range(start, stop[, step])

• 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.

For -ve step, the contents of the range are


range(0, 10, 3) range(-10, -100)
still given by the same formula but
0, 3, 6, 9 <empty> i >= 0 and r[i] > stop.

range(-10, -100, -20) range(-10, -20, -2)


-10, -30, -50, -70, -90 -10, -12, -14, -16, -18

Default begin from 0. It is possible to let the range


start at another number, or to specify a different empty step
increment (or step) than 1 (even a negative value). 1
45
The range() Function
• More examples:

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

• Used for updating a list:


lyrics = ['Mary', 'had', 'a', 'little', 'lamb']
for i, word in enumerate(lyrics):
print(i, word) 0 Mary
lyrics[i] = lyrics[i].swapcase() 1 had
2a
print(lyrics) 3 little
4 lamb
['mARY', 'HAD', 'A', 'LITTLE', 'LAMB']
51
Nested for Loops
• Nested loops: a loop within the body of another loop
• Examples: printing "ASCII triangles"
for i in range(1, 6): h=9 A
for j in range(i): ascii = 65 # ASCII value of 'A' BB
print(i, end=' ') for i in range(0, h): CCC
print() ch = chr(ascii) DDDD
if (i < h//2): EEEEE
1 for j in range(0, i+1): FFFF
22 print(ch, end=' ') GGG
333 else: HH
4444 for j in range(0, h-i): I
55555 print(ch, end=' ')
ascii += 1
print()

52

You might also like