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

Week 3

The document covers concepts of branching and iterations in programming, focusing on if-else statements, loops, and conditional operators. It includes examples of while and for loops, the use of the break statement, and practical exercises for generating random numbers and manipulating strings. Additionally, it discusses programming exercises related to ASCII values, counting occurrences of letters, and identifying capital letters in a string.

Uploaded by

2023ee72
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)
3 views52 pages

Week 3

The document covers concepts of branching and iterations in programming, focusing on if-else statements, loops, and conditional operators. It includes examples of while and for loops, the use of the break statement, and practical exercises for generating random numbers and manipulating strings. Additionally, it discusses programming exercises related to ASCII values, counting occurrences of letters, and identifying capital letters in a string.

Uploaded by

2023ee72
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

1

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

• then prints a string with that number of X’s.

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 = ‘’

#concatenate X to to_print num_x times


print(to_print)

• We would like to write a program that looks like above pseudocode


• When we want a program to do the same thing many times, we can use
iteration.

6
Iterations
• Also called looping mechanism is shown.

• Begins with a test.

• If the test evaluates to True, the program


executes the loop body once, and then
goes back to reevaluate the test.

• This process is repeated until the test


evaluates to False, after which control
passes to the code following the iteration
statement.
7
The while Loop
while <condition>:
<expression>
<expression>
...

• <condition> evaluates to a Boolean


• if <condition> is True, do all the steps inside the while code block
• check <condition> again
• repeat until <condition> is False

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

• Iterate through numbers in a sequence

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)

• change the assignment statement to ans = ans + abs(x), the code


works for negative numbers as well.

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.

• This function is defined in random module.

• # Program to generate a random number between 0 and 9

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

132 is divisible by 11 and 12

19
The for Loop
• The general form of a for statement is:

for variable in sequence:


code block

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

• The sequence of values bound to variable is most commonly generated


using the built-in function range, which returns a series of integers.
• 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

23
range(start,stop,step)
• The range function takes three integer arguments: start, stop, and
step.

• Produces: start, start + step, start + 2*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.

• If the first argument is omitted it defaults to 0

• If the last argument (the step size) is omitted it defaults to 1.

• range(0, 3) and range(3) both produce the sequence 0, 1, 2.

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}’)

• Unlike while, the number of iterations is not controlled by an explicit test,


and the index variable num_iters is not explicitly incremented

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

• How many times is each of the two loops executed?

36
The Nested for Loop
x = 4
for j in range(x):
for i in range(x):
x = 2

• There are four iterations of the outer loop.


• The inner for loop is reached four times.
• The first time it is reached, x = 4 and there will be 4 iterations.
• Next 3 times it is reached, x = 2, there will be 2 iterations each time.

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)

• What happens in this program?

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

The for loop The while loop


• 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 increment it
inside loop
• can rewrite a for loop
using a while loop • may not be able to rewrite a while
loop using a for loop
42
String Manipulation
• these two code snippets do the same thing, 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”)

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)

• The chr() method in Python returns a string representing a character and


a Unicode code integer. chr(98) returns the text ‘b’, chr()

48
Programming Exercise
• Converting Integers to Emojis

• We can also display emojis e.g., chr(0x1F600)

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

• Type a line of text:


▪ THE QUICK BROWN FOX JUMPED.
▪ First capital = B Last capital = X

50
Homework
• Count Number of Occurrences of a Letter
• Write a program to check the number of occurrences of a letter in the
sentence.

• Counting Vowels in a Sentence


• Write a script that reads a phrase and calculates the number of
vowels “aeiou” used in it. Count all the vowels in the given string and
output this number to the user.

51
Homework
• Write a program that reads a string of capital letters and displays the
longest sequence of consecutive alphabetically increasing capital
letters read.

• ENTER A STRING OF CAPITAL LETTERS: FGHADEFGHC

• THE LONGEST CONSECUTIVELY INCREASING STRING IS: DEFGH

52

You might also like