Week 3
Week 3
Week3
Branching and Iterations: If-Else,
Loops, Conditional Operators,
Break.
Reading:
▪ Chapter 2 of Guttag’s Book
2
Iterations
• Consider writing a program that asks the user how many time he wants to
print the letter X, and
3
Iterations
num_x = int(input(‘How many times should I print the
letter X? ‘))
to_print = ‘’
if num_x == 1:
to_print = 'X'
elif num_x == 2:
to_print = 'XX'
elif num_x == 3:
to_print = 'XXX'
#…
print(to_print)
4
Iterations
num_x = int(input(‘How many times should I print the
letter X? ‘))
to_print = ‘’
we would need as many
if num_x == 1: conditionals as there are
to_print = 'X' positive integers − there are
elif num_x == 2: an infinite number of integers.
to_print = 'XX'
elif num_x == 3:
to_print = 'XXX'
#…
print(to_print)
5
Iterations
num_x = int(input('How many times should I print the
letter X? ‘))
to_print = ‘’
6
Iterations
• Also called looping mechanism is shown.
8
The while Loop
n = input("You're in the Lost Forest. Go left, or right?")
while n == "right":
n = input("You're in the Lost Forest. Go left, or right?")
print("You got out of the Lost Forest!")
9
The while Loop
n = 0
while n < 5:
print(n)
n = n + 1
10
Square of an Integer
# Square an integer
x = 3
ans = 0
num_iters = 0
while (num_iters < x):
ans = ans + x
num_iters = num_iters + 1
print(f’{x}*{x} = {ans}’)
11
Square of an Integer
# Square an integer
x = 3
ans = 0
num_iters = 0
while (num_iters < x):
ans = ans + x
num_iters = num_iters + 1
print(f’{x}*{x} = {ans}’)
12
Square of a Negative Integer
• change the test to num_iters < abs(x)
13
This Program has a Bug!
• Change one line to avoid the infinite loop. For a few pairs of inputs, write
what the program does and what it’s supposed to do.
num = 8
guess = int(input("Guess my number: "))
while guess != num:
guess = input("Guess again: ")
print("Right!")
14
Programming Exercise
• Write a program that asks a user whether they want to play a game.
• If the user enters ‘y’ or ‘Y’, indicate that the computer is thinking of a
number between 0 and 9.
• Generate a number randomly. Ask the user to guess that number.
• Your program should continue asking the user to guess the number until
they get it right. If they get it right, print a congratulatory message and then
ask if they want to play again.
• This process should be repeated as long as the user enters ‘y’ or ‘Y’.
15
randint()
• To generate random number in Python, randint() function is used.
import random
random.randint(0,9)
16
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>
17
The break statement
#Find a positive integer that is divisible by both 11 and 12
x = 1
while True:
if x%11 == 0 and x%12 == 0:
break
x = x + 1
print(x, 'is divisible by 11 and 12’)
18
The break statement
#Find a positive integer that is divisible by both 11 and 12
x = 1
while True:
if x%11 == 0 and x%12 == 0:
break
x = x + 1
print(x, 'is divisible by 11 and 12’)
19
The for Loop
• The general form of a for statement is:
• The variable following for is bound to the first value in the sequence,
and the code block is executed.
• The variable is then assigned the second value in the sequence, and the
code block is executed again.
• The process continues until the sequence is exhausted or a break
statement is executed within the code block.
20
The for Loop
total = 0
for num in (77, 11, 3):
total = total + num
print(total)
• prints?
21
The for Loop
total = 0
for num in (77, 11, 3):
total = total + num
print(total)
• prints: 91
• The expression (77, 11, 3) is a tuple
▪ a tuple is a sequence of values
▪ Will be discussed later
22
The for Loop
for <variable> in range(<some_num>):
<expression>
<expression>
...
23
range(start,stop,step)
• The range function takes three integer arguments: start, stop, and
step.
• If step is positive, the last element is the largest integer such that (start
+ i*step) is strictly less than stop.
• If step is negative, the last element is the smallest integer such that
(start + i*step) is greater than stop.
24
range(start,stop,step)
• range(5, 40, 10) yields the sequence 5, 15, 25, 35,
• range(40, 5, -10) yields the sequence 40, 30, 20, 10.
25
range(start,stop,step)
x = 4
for i in range(x):
print(i)
• Prints?
26
range(start,stop,step)
x = 4
for i in range(x):
print(i)
0
1
2
3
27
The for Loop
# Square an integer
x = 3
ans = 0
num_iters = 0
for num_iters in range (abs(x)):
ans = ans + abs(x)
print(f’{x}*{x} = {ans}’)
28
The for Loop
• What happens if the index variable is modified within the for loop.
for i in range(2):
print(i)
i = 0
print(i)
• Prints?
29
The for Loop
• What happens if the index variable is modified within the for loop.
for i in range(2):
print(i)
i = 0
print(i)
0
0
1
0
30
The for Loop
• The above for loop is equivalent to the code
index = 0
last_index = 1
while index <= last_index:
i = index
print(i)
i = 0
print(i)
index = index + 1
• Code with the while loop is considerably more cumbersome than
the for loop.
31
The for Loop
x = 1
for i in range(x):
print(i)
x = 4
• prints?
32
The for Loop
x = 1
for i in range(x):
print(i)
x = 4
0
• The arguments to the range function in the line with for are evaluated
just before the first iteration of the loop, and not reevaluated for
subsequent iterations.
33
The Nested for Loop
x = 3
for j in range(x):
print('Iteration of outer loop’)
for i in range(x):
print(' Iteration of inner loop’)
x = 2
34
The Nested for Loop
Iteration of outer loop
Iteration of inner loop
Iteration of inner loop
Iteration of inner loop
Iteration of outer loop
Iteration of inner loop
Iteration of inner loop
Iteration of outer loop
Iteration of inner loop
Iteration of inner loop
35
The Nested for Loop
x = 4
for j in range(x):
for i in range(x):
x = 2
36
The Nested for Loop
x = 4
for j in range(x):
for i in range(x):
x = 2
37
The in operator
The for statement can be used in conjunction with the in operator to
conveniently iterate over characters of a string.
total = 0
for c in '12345678’:
total = total + int(c)
print(total)
• sums the digits in the string denoted by the literal '12345678' and prints
the total.
38
The for Loop
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
mysum += 1
print(mysum)
39
The for Loop
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
mysum += 1
print(mysum)
•5
40
The while vs for
• # more complicated with • # shortcut with for loop
while loop
n = 0 for n in range(5):
while n < 5: print(n)
print(n)
n = n+1
41
The while vs for
• can end early via break • can end early via break
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”)
43
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):
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, "!!!")
44
Robot Cheerleaders
an_letters = “aefhilmnorsxAEFHILMNORSX”
word = input("I will cheer for you! Enter a word: ")
times = int(input("Enthusiasm level (1-10): "))
i = 0
for char in word:
if char in an_letters:
print("Give me an " + char + "! " + char)
else:
print("Give me a " + char + "! " + char)
print("What does that spell?")
for i in range(times):
print(word, "!!!")
45
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
46
Programming Exercise
• Write a program that prints ASCII Values of all Characters
47
Programming Exercise
• Write a program that prints ASCII Values of all Characters
print("ASCII\tCharacter")
for i in range(256):
ch = chr(i)
print(i, "\t\t", ch)
48
Programming Exercise
• Converting Integers to Emojis
chr(0x1F601)
49
Programming Exercise
• Prompt the user to enter a line of text.
• Display the capital letter entered that comes first alphabetically and the
one that comes last.
• If no capital letters are entered, display “No capital letters”.
50
Homework
• Count Number of Occurrences of a Letter
• Write a program to check the number of occurrences of a letter in the
sentence.
51
Homework
• Write a program that reads a string of capital letters and displays the
longest sequence of consecutive alphabetically increasing capital
letters read.
52