0% found this document useful (0 votes)
1 views

lec2-conditional-and-interation

The lecture covers branching and iteration in Python, focusing on conditionals, loops, and their syntax. Key concepts include comparison and logic operators, the importance of indentation, and the use of 'if', 'while', and 'for' statements for control flow. Additionally, it discusses runtime implications of branching and looping structures, along with best practices for optimizing loops.

Uploaded by

Michael Chu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

lec2-conditional-and-interation

The lecture covers branching and iteration in Python, focusing on conditionals, loops, and their syntax. Key concepts include comparison and logic operators, the importance of indentation, and the use of 'if', 'while', and 'for' statements for control flow. Additionally, it discusses runtime implications of branching and looping structures, along with best practices for optimizing loops.

Uploaded by

Michael Chu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Lecture 2

Branching and Iteration


GNBF5010
Instructor: Jessie Y. Huang
RECAP …
• Syntax
• Scalar objects
• Simple operations
• Expressions, variables and values

2
TODAY …
• Branching and conditionals
• Indentation
• Iteration and loops

3
BRANCHING &
CONDITIONALS

4
COMPARISON OPERATORS ON
int, float AND string
• i and j are variable names
• comparisons below evaluate to a Boolean
i > j
i >= j
i < j
i <= j
i == j → equality test, True if i is the same as j
i != j → inequality test, True if i is not the same as j
5
LOGIC OPERATORS ON bools
• a and b are variable names (with Boolean values)

not a → True if a is False; False if a is True


a and b → True if both are True
a or b → True if either or both are True

6
BRANCHING PROGRAMS
• The simplest branching statement is a
conditional
• A test (expression that evaluates to
True or False)
• A block of code to execute if the test is
True
• An optional block of code to execute if
the test is False

7
A SIMPLE EXAMPLE
x = int(input('Enter an integer: '))
if x%2 == 0:
print(’’)
print('Even’)
else:
print(’’)
print('Odd')
print('Done with conditional')

8
A SIMPLE EXAMPLE - SOME OBSERVATIONS
• The expression x%2 == 0 evaluates to True when the
remainder of x divided by 2 is 0
• Note that == is used for comparison, since = is reserved for
assignment
• The indentation is important – each indented set of expressions
denotes a block of instructions
• For example, if the last statement were indented, it would be executed
as part of the else block of code
• Note how this indentation provides a visual structure that reflects
the semantic structure of the program

9
NESTED CONDITIONALS
if x%2 == 0:
if x%3 == 0:
print('Divisible by 2 and 3')
else:
print('Divisible by 2 and not by 3’)
elif x%3 == 0:
print('Divisible by 3 and not by 2')

10
COMPOUND BOOLEANS

if x < y and x < z:


print('x is least')
elif y < z:
print('y is least')
else:
print('z is least')

11
CONTROL FLOW - BRANCHING
if <condition>: if <condition>: if <condition>:
<expression> <expression> <expression>
<expression> <expression> <expression>
... ... ...
else: elif <condition>:
<expression> <expression>
<expression> <expression>
... ...
else:
<expression>
<expression>
• <condition> has a value of True or False ...

• expressions in that block will be evaluated if


<condition> is True

12
BRANCHING EXAMPLE

13
INDENTATION
• determines how you x = float(input("Enter a number for x: "))
denote blocks of code y = float(input("Enter a number for y: "))
• matters in Python if x == y:
print("x and y are equal" )
• use FOUR spaces for one if y != 0
0:
indentation print("therefore, x / y is", x/y)
x/y)
elif x < y:
print("x is smaller"
smaller")
)
else:
print("y is smaller")
smaller")
print("thanks!")

14
= vs ==
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")

15
RUNNING TIME
• Branching programs allow us to make choices and do different things.
• But still the case that at most, each statement gets executed once.
• So maximum time to run the program depends only on the length
of the program.
• These programs run in constant time.

16
Exercise 1
Write a Python program to get the difference between a given number
and 17, but if the number is greater than 17, print double the absolute
difference.
For example, if the input number is 22, the program gives 10, while
input 14 gives 3.

17
ITERATION
while LOOP

18
CONTROL FLOW: while LOOPS
while <condition>:
<expression>
<expression>
...
1. <condition> evaluates to a Boolean
2. if <condition> is True, do all the steps inside the code block
3. check <condition> again
4. repeat until <condition> is False

19
while LOOP EXAMPLE:
INPUT VALIDATION LOOPS

20
while LOOP EXAMPLE:
INPUT VALIDATION LOOPS

• It determines whether score is less than 0 or greater than 100.


• If either is true, an error message displays, and the user is prompted to
enter a correct score.

21
CONTROL FLOW: while LOOPS
Some properties of while loops:
• need to set initial condition outside the loop
• need to test condition to determine when to exit the loop
• need to change variable within the loop

22
while LOOP EXAMPLE:
PERFECT SQUARES
• prints the square root if x is a perfect square (pretend sqrt() is not available)
ans = 0
if ans**2 == x:
neg_flag = False
print(f"Square root of {x} is {ans}.")
x = int(input("Enter an integer: "))
else:
if x < 0:
print(f"{x} is not a perfect square.")
neg_flag = True if neg_flag:
while ans**2 < x: print(f"Did you mean {-x}?")
ans += 1

What's printed when x = 4, 5, 0 and -2?


23
ITERATION
for LOOP

24
CONTROL FLOW: for LOOPS
• To iterate through numbers in a sequence:
# more complicated with while loop
n = 0
while n < 5:
print(n)
n += 1

# shortcut with for loop


for n in range(5):
print(n)
25
CONTROL FLOW: for LOOPS
for <variable> in range(<some_num>):
<expression>
<expression>
...

• each time through the loop, <variable> takes a value


• first time, <variable> starts at the smallest value
• next time, <variable> gets the previous value + 1
• etc.
26
range(start,stop,step)
• default values are start = 0 and step = 1 , optional
• loop until value is stop - 1

mysum = 0
for i in range(7, 10):
mysum += i
print(mysum)

mysum = 0
for i in range(5, 11, 2):
mysum += i
print(mysum)

27
while LOOP vs for LOOP

28
for LOOPS vs while LOOPS
for loops while loops
• know number of iterations • unbounded number of
iterations
• can end early via break • can end early via break
• uses a counter • can use a counter but must
initialize before loop and
update it inside loop
• can rewrite a for loop • may not be able to rewrite
using a while loop a while loop using a for
loop
29
ITERATION
• Start with a test
• If evaluates to True, then execute loop block
once, and go back to re-evaluate the test
• Repeat until test evaluates to False, after which
code following iteration statement is executed

30
ITERATION
break and continue

31
THE break STATEMENT
• immediately exits whatever loop it is in
• skips remaining expressions in code block
• exits only innermost loop!

while <condition_1>:
while <condition_2>:
<expression_a>
break
<expression_b>
<expression_c>

32
THE break STATEMENT
mysum = 0
for i in range(5, 11, 2):
mysum +=
mysum += i
i
if mysum == 5
5::
break
mysum += 1
print(mysum)

what happens in this program?

33
THE continue STATEMENT
• only skips the remaining statements of the current loop
• then continues to the next loop

while <condition_1>:
while <condition_2>:
<expression_a>
continue
<expression_b>
<expression_c>

34
ITERATION
STRINGS AND LOOPS

35
STRINGS AND LOOPS
▪ a for-loop variable can iterate over any set of values, not just numbers!
▪ these two code snippets do the same thing
▪ the bottom one is more “pythonic”
s = "abcdefgh"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u’:
print("There is an i or u")

for char in s:
if char == 'i' or char == 'u':
print("There is an i or u")
36
CODE EXAMPLE 1: ROBOT CHEERLEADERS
an_letters = "aefhilmnorsxAEFHILMNORSX"

word = input("I will cheer for you! Enter a word: ")


times = int(input("Enthusiasm level (1-10): "))

i = 0
while i < len(word): for char in word:
char = word[i]
if char in an_letters:
print("Give me an " + char + "! " + char)
else:
print("Give me a " + char + "! " + char)
i += 1
print("What does that spell?")
for i in range(times):
print(word, "!!!")
37
CODE EXAMPLE 2: COUNTING STOP CODONS
▪ Count the number of potential stop codons “TAG”, “TAA”, or “TGA” that
occur in the sequence.
How to loop over the sequence? What's the index range?

len(seq) = 14 i i=len(seq)-3

0 1 2 3 4 5 6 7 8 9 10 11 12 13

seq[0:3] seq[12:14]
seq[1:4]

38
CODE EXAMPLE 2: COUNTING STOP CODONS
seq = "ATAGAGACTAGACT"
print(seq)

stop_counter = 0
for i in range(0, len(seq) - 3 + 1):
codon = seq[i:i + 3]
#print(codon)
if codon == "TAG" or codon == "TAA" or codon == "TGA":
#print("stop codon", codon, "found!")
stop_counter += 1
print("Number of stop codons:", stop_counter)

39
CODE EXAMPLE 2: COUNTING STOP CODONS
Alternatively, use while-loop to access indices easily.
seq = "ATAGAGACTAGACT"
#print(seq)

stop_counter = 0
i = 0
while i <= len(seq) - 3:
codon = seq[i:i + 3]
#print(codon)
if codon == "TAG" or codon == "TAA" or codon == "TGA":
#print("stop codon", codon, "found!")
stop_counter += 1
i += 1
print("Number of stop codons:", stop_counter) 40
EXERCISE
s1 = "mit u rock"
s2 = "i rule mit"
if len(s1) == len(s2):
for char1 in s1:
for char2 in s2:
if char1 == char2:
print("common letter")
break
How many lines will the code above print "common letter"?
A. 1 B. 2 C. 5 D. 7 E. 10
41
ITERATION
RUNTIME

42
RUNTIME
• Branching structures (conditionals) let us jump to different pieces
of code based on a test
• Programs take constant time
• Looping structures (e.g., while) let us repeat pieces of code if a
condition is satisfied
• Programs now take time that depends on values of variables (counter), as well
as length of program
• Be cautious when using nested loops, because the runtime may increase
exponentially: n2 for a 2-level nested loop, n3 for 3-level, n4 for 4-level, ...
• Try to minimize the length of program inside the loop, especially the innermost
loop

43
GOOD PRACTICE
• The key to optimizing loops is to minimize what they do.
• Even operations that appear to be fast will take long time if repeated many times.
• Example: Don't execute things like len(list) inside a loop or even in its test condition.

https://www.tutorialspoint.com/What-are-the-best-practices-for-using-loops-in-Python
44
EXERCISE 2
Write a program that asks the user to enter the starting number (integer), ending
number (integer) and the word "even" or "odd". Then generate a customized
printout based on their input.
Here's a sample running of the program:
Starting number: 5
Ending number: 15
Even or Odd?: even
6
8
10
12
14

45
READING MATERIALS
• Chapters 3 & 4, Starting out with Python 4/e.
• good for beginners

• Chapters 2, 3 & 5, Python for Everybody by Charles Severance


• Lecture videos by the book author
• https://www.py4e.com/lessons/memory
• https://www.py4e.com/lessons/logic
• https://www.py4e.com/lessons/loops

• Chapters 2.2, 2.3.1, 2.4, 3.1 & 3.2, Guttag's Introduction to Computation
and Programming using Python.
• a bit advanced
46

You might also like