5 Chapter
5 Chapter
Loop concept
©zyBooks 01/03/22 22:04 1172417
People who have children may be familiar with looping around the block until a baby falls asleep.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
5.1.1:
Loop concept: Driving a baby around the block.
Animation captions:
1. Parents may be familiar with this scenario: Driving home, baby is awake. Parents circle the
block, hoping the baby will fall asleep.
2. After first loop, baby is still awake, so parents loop again.
3. After second loop, baby is asleep, so parents head home for a peaceful evening.
PARTICIPATION
ACTIVITY
5.1.2:
Loop concept.
awake?
Bharathi Byreddy
Yes LOUISVILLEMSBAPrep2DaviesWinter2022
No
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 1/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Loop basics
A loop is a program construct that repeatedly executes the loop's statements (known as the loop
body) while the loop's expression is true; when false, execution proceeds past the loop. Each time
through a loop's statements is called an iteration.
PARTICIPATION
ACTIVITY
5.1.3:
A simple loop: Summing the input values.
Animation captions:
1. A loop is like a branch, but jumping back to the expression when done. Thus, the loop's
statements may execute multiple times, before execution proceeds past the loop.
2. This program gets an input value. If the value > -1, the program adds the value to a sum, gets
another input, and repeats. val is 2, so the loop's statements execute, making sum 2.
3. The loop's statements ended by getting the next input, which is 4. The loop's expression 4 > -1
is true, so the loop's statements execute again, making sum 2 + 4 or 6.
4. The loop's statements got the next input of 1. The loop's expression 1 > -1 is true, so the loop's
statements execute a third time, making sum 6 + 1 or 7.
5. The next input is -1. This time, -1 > -1 is false, so the loop is not entered. Instead, execution
proceeds past the loop, where a statement puts sum, which is 7, to the output.
ACTIVITY
5.1.4:
Loop example: Computing an average. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Animation captions:
1. The program computes an average of a list of numbers (a negative ends the list). The first
input is 2, so the loop is entered. Sum becomes 2, and num is incremented to 1.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 2/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
2. The next input is 4. The loop is entered, so sum becomes 2 + 4 or 6, and num is incremented
to 2.
3. The next input is 9, so the loop is entered. Sum becomes 6 + 9 or 15, and num is incremented
to 3.
4. The next input is -1, so the loop is not entered. 15 / 3 or 5 is output.
ACTIVITY
5.1.5:
Loop example: Average. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
LOUISVILLEMSBAPrep2DaviesWinter2022
1
2
3
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 3/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Programs execute one statement at a time. Thus, using a loop to examine a list of values one value at
a time and updating variables along the way, as in the above examples, is a common programming
task.
Below is a task to help a person get accustomed to examining a list of values one value at a time. The
task asks a person to count the number of negative values, incrementing a variable to keep count.
PARTICIPATION
ACTIVITY
5.1.6:
Counting negative values in a list of values.
Start
Counter
X X X X X X X 0
PARTICIPATION
ACTIVITY 5.1.7:
Counting negative values.
Complete the program such that variable count ends having the number01/03/22
©zyBooks of negative
22:04values
1172417
Bharathi Byreddy
in an input list of values (the list ends with 0). So if the input is -1 -5 9 3 0, then count should
LOUISVILLEMSBAPrep2DaviesWinter2022
end with 2.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 4/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
count = 0
if __(A)__
__(B)__
LOUISVILLEMSBAPrep2DaviesWinter2022
val > 0
val < 0
val is 0
Examining items one at a time and updating a variable can achieve some interesting computations.
The task below is to find the maximum value in a list of positive values. A variable stores the max
value seen so far. Each input value is compared with that max, and if greater, that value replaces that
max. The max value is initialized with -1 so that such comparison works even for the first input value.
PARTICIPATION
ACTIVITY
5.1.8:
Find the maximum value in the list of values.
Bharathi Byreddy
Start LOUISVILLEMSBAPrep2DaviesWinter2022
max
X X X X X X X
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 5/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
ACTIVITY 5.1.9:
Determining the max value. LOUISVILLEMSBAPrep2DaviesWinter2022
Complete the program such that variable max ends having the maximum value in an input
list of positive values (the list ends with 0). So if the input is 22 5 99 3 0, then max should end
as 99.
max = -1
If __(A)__
__(B)__
Bharathi Byreddy
Yes LOUISVILLEMSBAPrep2DaviesWinter2022
No
-1, 5, 10, 7, 20
Bharathi Byreddy
A while loop is a construct that repeatedly executes an indented block of code (known as the loop
body) as long as the loop's expression is True. At the end of the loop body, execution goes back to the
while loop statement and the loop expression is evaluated again. If the loop expression is True, the
loop body is executed again. But, if the expression evaluates to False, then execution instead proceeds
to below the loop body. Each execution of the loop body is called an iteration, and looping is also
called iterating.
PARTICIPATION
ACTIVITY
5.2.1:
While loop.
Animation content:
undefined
Animation captions:
©zyBooks 01/03/22 22:04 1172417
5. user_char is now 'n', so user_char == 'y' is false. Thus, execution jumps to after the loop, which
outputs "Done".
PARTICIPATION
ACTIVITY
5.2.2:
Basic while loops.
For each question, indicate how many times will the loop body©zyBooks
execute?01/03/22 22:04 1172417
Bharathi Byreddy
1) x = 3
LOUISVILLEMSBAPrep2DaviesWinter2022
while x >= 1:
# Do something
x = x - 1
# Do something
# Do something
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
The following example uses the statement while user_value != 'q': to allow a user to end a
face-drawing program by entering the character 'q'. The letter 'q' in this case is a sentinel value, a value
that when evaluated by the loop expression causes the loop to terminate.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 8/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
The code print(user_value*5) produces a new string, which repeats the value of user_value 5
times. In this case, the value of user_value may be "-", thus the result of the multiplication is "-----".
Another valid (but long and visually unappealing) method is the statement
print(f'{user_value}{user_value}{user_value}{user_value}{user_value}').
Note that input may read in a multi-character string from the user, so only the first character is
extracted from user_input with user_value = user_input[0].
©zyBooks 01/03/22 22:04 1172417
Once execution enters the loop body, execution continues to the body's end evenByreddy
Bharathi if the expression
Figure 5.2.1: While loop example: Face-printing program that ends when
user enters 'q'.
- -
user_value = '-'
-----
eyes
0
print('\n')
quit): @
quit): \n")
@@@@@
user_value = user_input[0]
print('Goodbye.\n')
Enter a character ('q' for
quit): q
Goodbye.
PARTICIPATION
ACTIVITY
5.2.3:
Loop expressions.
Complete the loop expressions, using a single operator in your expression. Use the most
straightforward translation of English to an expression. ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
1) Iterate while x is less than 100.
while :
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 9/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
The following program animation provides another loop example. First, the user enters an integer.
Then, the loop prints each digit one at a time starting from the right, using "% 10" to get the rightmost
digit and "// 10" to remove that digit. The loop is only entered while num is greater than 0; once num
reaches 0, the loop will have printed all digits.
PARTICIPATION
ACTIVITY 5.2.4:
While loop step-by-step.
Animation content:
undefined
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
1. User enters the number 902. The first iteration prints "2".
2. The second iteration prints "0".
3. The third iteration prints "9", so every digit has been printed. The loop condition is checked one
more time, and since num is 0, the loop stops.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 10/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
Each iteration of the program below prints one line with the year and the number of ancestors in that
year. (Note: the program's output numbers are largely due to not considering breeding among distant
relatives, but nevertheless, a person has many ancestors.)
The program checks for year_considered >= user_year rather than for
year_considered != user_year, because year_considered might be reduced
©zyBooks 01/03/22past user_year
22:04 1172417
Bharathi Byreddy
without equaling it, causing an infinite loop. An infinite loop is a loop that will always execute because
LOUISVILLEMSBAPrep2DaviesWinter2022
the loop's expression is always True. A common error is to accidentally create an infinite loop by
assuming equality will be reached. Good practice is to include greater than or less than along with
equality in a loop expression to help avoid infinite loops.
A program with an infinite loop may print output excessively, or just seem to stall (if the loop contains
no printing). A user can halt a program by pressing Control-C in the command prompt running the
Python program. Alternatively, some IDEs have a "Stop" button.
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 11/71
1/3/22, 10:06 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY 5.2.5:
While loop iterations.
What is the output of the following code? (Use "IL" for infinite loops.)
1) x = 0
©zyBooks 01/03/22 22:04 1172417
while x > 0:
Bharathi Byreddy
print('Bye')
2) x = 5
y = 18
while y >= x:
y = y - x
3) x = 10
while x != 3:
x = x / 2
4) x = 1
y = 3
z = 5
x = x + 1
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
5.2.1:
Enter the output of the while loop.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 12/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
368708.2344834.qx3zqy7
Start
g = 0
0
©zyBooks 01/03/22 22:04 1172417
while g <= 1:
1
Bharathi Byreddy
print(g)
LOUISVILLEMSBAPrep2DaviesWinter2022
g += 1
1 2 3 4
Check Next
CHALLENGE
ACTIVITY 5.2.2:
Basic while loop with user input.
Write an expression that executes the loop body as long as the user enters a non-negative
number.
Note: If the submitted code has an infinite loop, the system will stop running the code after a
few seconds and report "Program end never reached." The system doesn't print the test case
that caused the reported message.
Body
Body
Body
Done.
LOUISVILLEMSBAPrep2DaviesWinter2022
1 user_num = int(input())
2 while ''' Your solution goes here ''':
3 print('Body')
4 user_num = int(input())
5
6 print('Done.')
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 13/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
5.2.3:
Basic while loop expression.
Write a while loop that repeats while user_num ≥ 1. In each loop iteration, divide user_num by
2, then print user_num.
10.0
5.0
2.5
1.25
0.625
Note: If the submitted code has an infinite loop, the system will stop running the code after a
few seconds and report "Program end never reached." The system doesn't print the test case
that caused the reported message.
368708.2344834.qx3zqy7
1 user_num = int(input())
2
3 ''' Your solution goes here '''
4
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 14/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Run
LOUISVILLEMSBAPrep2DaviesWinter2022
Example: GCD
The following is an example of using a loop to compute a mathematical quantity. The program
computes the greatest common divisor (GCD) among two user-entered integers num_a and num_b,
using Euclid's algorithm: If num_a > num_b, set num_a to num_a - num_b, else set num_b to
num_b - num_a. Repeat until num_a equals num_b, at which point num_a and num_b both equal the
GCD.
20
14 Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
5.3.1:
Loop example: Greatest common divisor.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 15/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer
the questions by mentally executing the statements. If stuck, consider adding additional print
statements to the program.
Bharathi Byreddy
Example: Conversation
Below is a program that has a "conversation" with the user. The program asks the user to type
something and then randomly prints one of four possible responses until the user enters "Goodbye".
Note that the first few lines of the program represent a docstring: a multi-line string literal delimited at
the beginning and end by triple-quotes. Either single ' or double "©zyBooks
quotes can01/03/22 22:04 1172417
be used.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 16/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Load default template...
1 '''
2 Program that has a conversation with the user.
3 Uses elif branching and a random number to mix up the pro
4 '''
5 import random # Import a library to generate random numb
6
7 print('Tell me something about yourself.')©zyBooks 01/03/22 22:04 1172417
9 LOUISVILLEMSBAPrep2DaviesWinter2022
10 user_text = input()
11
12 while user_text != 'Goodbye':
13 random_num = random.randint(0, 2) # Gives a random i
14 if random_num == 0:
15 print('\nPlease explain further.\n')
16 elif random_num == 1:
17 print(f"\nWhy do you say: '{user_text}'?\n")
Goodbye
Run
Each time through the while loop, the program will check if the user-entered string user_text is equal
to the string literal "Goodbye". If the two strings are not equal, the while loop body executes. Within the
while loop body, the program obtains a random number between 0 and 2 by using the random library.
The randint() function provides a new random number each time the function is called. The
arguments to randint(), 0 and 2, provide the minimum and maximum values that the function may
return. Using the number given by randint(), the program's elif statements branch to a particular
response.
PARTICIPATION
ACTIVITY 5.3.2:
Conversation program.
LOUISVILLEMSBAPrep2DaviesWinter2022
1) Which if-else branch will execute if
the user types "Goodbye"?
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
3) Write an expression using
random.randint() that returns a
number between 0 and 5, inclusive.
Loops are commonly used to process a series of input values. A sentinel value is used to terminate a
loop's processing. The example below computes the average of an input list of positive integers,
ending with 0. The 0 is not included in the average.
1 '''
2 Outputs average of list of positive integers
3 List ends with 0 (sentinel)
4 Ex: 10 1 6 3 0 yields (10 + 1 + 6 + 3) / 4, or 5
5 '''
6
7 values_sum = 0
8 num_values = 0
9
10 curr_value = int(input())
11 ©zyBooks 01/03/22 22:04 1172417
10
3
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 18/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Run
ACTIVITY
5.3.3:
Average example with a sentinel.
LOUISVILLEMSBAPrep2DaviesWinter2022
Consider the example above and the given example input sequence 10 1 6 3 0.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
5.3.1:
While loop with sentinel.
368708.2344834.qx3zqy7
Start
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 19/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Input
user_value = int(input())
2
minimum_value = user_value
34
12
0
if user_value < minimum_value:
©zyBooks 01/03/22 22:04 1172417
minimum_value = user_value
Bharathi Byreddy
user_value = int(input())
LOUISVILLEMSBAPrep2DaviesWinter2022
Output
print('Min value:', minimum_value, end='')
Min value: 2
1 2
Check Next
CHALLENGE
ACTIVITY 5.3.2:
Bidding example.
Write an expression that continues to bid until the user enters 'n'.
Continue bidding?
368708.2344834.qx3zqy7
1 import random
2 random.seed(5)
3 ©zyBooks 01/03/22 22:04 1172417
5 next_bid = 0 LOUISVILLEMSBAPrep2DaviesWinter2022
6
7 while ''' Your solution goes here ''':
8 next_bid = next_bid + random.randint(1, 10)
9 print(f'I\'ll bid ${next_bid}!')
10 print('Continue bidding?', end=' ')
11 keep_bidding = input()
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 20/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Run
ACTIVITY
5.3.3:
While loop: Insect growth. LOUISVILLEMSBAPrep2DaviesWinter2022
Given positive integer num_insects, write a while loop that prints, then doubles, num_insects
each iteration. Print values ≤ 100. Follow each number with a space.
8 16 32 64
368708.2344834.qx3zqy7
Run
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
5.4 Counting
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 21/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Commonly, a loop should iterate a specific number of times, such as 10 times. The programmer can
use a variable to count the number of iterations, called a loop variable. To iterate N times using an
integer loop variable i, a loop1 with the following form is used:
Construct 5.4.1: Counting while loop form. ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
i = 1
while i <= N:
# Loop body statements go here
i = i + 1
A common error is to forget to include the loop variable update (e.g., i = i +1) at the end of the loop,
causing an unintended infinite loop.
The following program outputs the amount of money in a savings account each year for the user-
entered number of years, with $10,000 initial savings and 5% yearly interest:
zyDE 5.4.1: While loop that counts iterations: Savings interest program.
1 '''Program that calculates savings and interest'''
2
3 initial_savings = 10000
4 interest_rate = 0.05
5
6 print(f'Initial savings of ${initial_savings}')
7 print(f'at {interest_rate*100:.0f}% yearly interest.\n')
8
9 years = int(input('Enter years: '))
10 print()
11
12 savings = initial_savings
13 i = 1 # Loop variable ©zyBooks 01/03/22 22:04 1172417
15 LOUISVILLEMSBAPrep2DaviesWinter2022
print(f' Savings at beginning of year {i}: ${savings:
16 savings = savings + (savings*interest_rate)
17 i = i + 1 # Increment loop variable
10
Run
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 22/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY
5.4.1:
Savings interest program. ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Refer to the program above.
2) If interest_rate is 3% and
initial_savings are $5000, savings
will be greater than $7500 after
how many loop iterations?
PARTICIPATION
ACTIVITY 5.4.2:
Basic counting with while loops.
while :
Bharathi Byreddy
i = i + 1
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 23/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
i = 1
while :
i = i + 1
i = 1
LOUISVILLEMSBAPrep2DaviesWinter2022
while :
i = i + 1
Counting down is also common, as in counting down from 5 to 1. The loop body executes when i is 5,
4, 3, 2, and 1, but does not execute when i reaches 0.
i = 5
while i >= 1:
i = i - 1
The loop body executes when i is 5, 4, 3, 2, and 1, but does not execute when i reaches 0.
Counting sometimes occurs by steps greater than 1. Ex: A loop that prints even values from 0 to 100
(i.e., counts from 0 to 100 by 2s) is:
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
iteration.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 24/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
i = 0
i = i + 2
LOUISVILLEMSBAPrep2DaviesWinter2022
Write a program that prints the U.S. presidential election years from
1792 to present day, knowing that such elections occur every 4 years.
Hint: Initialize your loop variable to 1792. Don't forget to use <= rather
than == to help avoid an infinite loop.
1 year = 1792
2 current_year = ?
3
4 while year ? ??:
5 # Print the election year
6 year = year + ?
7
PARTICIPATION
ACTIVITY
5.4.3:
Forms of counting.
Bharathi Byreddy
while i <= 9:
while :
i = i + 5
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Check Show answer
i = i + 1
PARTICIPATION
ACTIVITY 5.4.4:
Counting in a loop simulator.
The following tool allows you to enter values for a loop's parts,
and then executes the loop. Using the tool, try to solve each
listed problem individually.
The tool can use any relational or equality operator, such as <, ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
<=, >, >=, ==, etc. Identity and membership operators like "is" or
LOUISVILLEMSBAPrep2DaviesWinter2022
"in" will not work.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 26/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
i =
while i :
Run code
print(i, end=' ')
©zyBooks 01/03/22 22:04 1172417
i = i
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
5
Load default template...
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Shorthand operators
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 27/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
num *= x + y is shorthand for num = num * (x + y). Usage of such operators is common in
loops.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
i = 0
while i < N:
i += 1
PARTICIPATION
ACTIVITY
5.4.5:
Shorthand operators.
Answer each question using the operators of the form +=, *=, /=, -=, etc.
ACTIVITY 5.4.1:
Loops with variables that count. LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7
Start
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 28/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
n = 1
while n <= 4:
3
print(n + 2)
n = n + 1
4
Bharathi Byreddy
1 2 LOUISVILLEMSBAPrep2DaviesWinter2022
3
Check Next
CHALLENGE
ACTIVITY
5.4.2:
While loop: Print 1 to N.
Write a while loop that prints from 1 to user_num, increasing by 1 each time.
368708.2344834.qx3zqy7
1 i = 1
2
3 user_num = int(input()) # Assume positive
4
5 ''' Your solution goes here '''
6
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 29/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Run
CHALLENGE
ACTIVITY 5.4.3:
Printing output using a counter.
Retype or copy, and then run the following code; note incorrect behavior. Then fix errors in
the code, which should print num_stars asterisks. ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
while num_printed != num_stars:
print('*')
368708.2344834.qx3zqy7
1 num_printed = 0
2
3 num_stars = int(input())
4
5 ''' Your solution goes here '''
6
Run
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
(*1) Focus is placed on mastering basic looping using while loops, before introducing for loops and
range().
Survey
The following questions are part of a zyBooks survey to help us improve our content so
we can offer the best experience for students. The survey can be taken anonymously
©zyBooks 01/03/22 22:04 1172417
and takes just 3-5 minutes. Please take a short moment to answer by clicking
Bharathi the
Byreddy
following link. LOUISVILLEMSBAPrep2DaviesWinter2022
Basics
A common programming task is to access all of the elements in a container. Ex: Printing every item in
a list. A for loop statement loops over each element in a container one at a time, assigning a variable
with the next element that can then be used in the loop body.
The container in the for loop statement
is typically a list, tuple, or string. Each iteration of the loop assigns the name given in the for loop
statement with the next element in the container.
Construct 5.5.1
PARTICIPATION
ACTIVITY
5.5.1:
Iterating over a list using a for loop.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
undefined
Animation captions:
1. The first iteration assigns the variable name with 'Bill' and prints 'Hi Bill!' to the screen.
2. The second iteration assigns the variable name with 'Nicole' and prints 'Hi Nicole!'.
3. The third iteration assigns the variable name with 'John' and prints 'Hi John!'.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 31/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
The for loop above iterates over the list ['Bill', 'Nicole', 'John']. The first iteration assigns
the variable name with 'Bill', the second iteration assigns name with 'Nicole', and the final iteration
assigns name with 'John'. For sequence types like lists and tuples, the assignment order follows the
position of the elements in the container, starting with position 0 (the leftmost element) and
continuing until the last element is reached.
©zyBooks 01/03/22 22:04 1172417
Iterating over a dictionary using a for loop assigns the loop variable withBharathi
the keysByreddy
of the
dictionary.
The values can then be accessed using the key. LOUISVILLEMSBAPrep2DaviesWinter2022
Figure 5.5.1: A for loop assigns the loop variable with a dictionary's keys.
channels = {
'MTV': 35,
'CNN': 28,
'FOX': 11,
MTV is on channel 35
'CBS': 12
FOX is on channel 11
NBC is on channel 4
CBS is on channel 12
for c in channels:
A for loop can also iterate over a string. Each iteration assigns the loop variable with the next
character of the string. Strings are sequence types just like lists, so the behavior is identical (leftmost
character first, then each following character).
my_str = ''
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
5.5.2:
Creating for loops.
Complete the for loop statement by giving the loop variable and container.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 32/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
For loops can be used to perform some action during each loop iteration. A simple example would be
printing the value, as above examples demonstrated. The program below uses an additional variable
to sum list elements to calculate weekly revenue and an average daily revenue.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 33/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
daily_revenues = [
2356.23, # Monday
1800.12, # Tuesday
1792.50, # Wednesday
2058.10, # Thursday
1988.00, # Friday
2002.99, # Saturday
1890.75 # Sunday
©zyBooks 01/03/22 22:04 1172417
total = 0
Bharathi Byreddy
A for loop may also iterate backwards over a sequence, starting at the last element and ending with
the first element, by using the reversed() function to reverse the order of the elements.
The following program first prints a list that is ordered alphabetically, then prints the same
list in reverse order.
names = [
'Biffle',
'Bowyer',
'Busch',
'Gordon',
'Patrick'
]
Biffle | Bowyer | Busch | Gordon | Patrick |
Printing in reverse:
print('\nPrinting in reverse:')
for name in reversed(names):
©zyBooks 01/03/22 22:04 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 5.5.3:
For loops.
num_kids = [1, 1, 2, 2, 1, 4,
3, 1]
total = 0
LOUISVILLEMSBAPrep2DaviesWinter2022
num_neg = 0
if temp < 0:
for scr in :
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
5.5.1:
Looping over strings, lists, and dictionaries.
368708.2344834.qx3zqy7
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 35/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Start
Type the program's output
grey
pink
print(color)
red
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
1 2 3 4
Check Next
CHALLENGE
ACTIVITY
5.5.2:
For loop: Printing a list
$ 34.62
$ 76.30
$ 85.05
368708.2344834.qx3zqy7
1 # NOTE: The following statement converts the input into a list container
2 stock_prices = input().split()
3
4 for ''' Your solution goes here ''':
5 print('$', price)
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 36/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Run
CHALLENGE
ACTIVITY
5.5.3:
For loop: Printing a dictionary
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
[email protected] is Alf
368708.2344834.qx3zqy7
1 contact_emails = {
2 'Sue Reyn' : '[email protected]',
3 'Mike Filt': '[email protected]',
4 'Nate Arty': '[email protected]'
5 }
6
7 new_contact = input()
8 new_email = input()
9 contact_emails[new_contact] = new_email
10
11 ''' Your solution goes here '''
12
Run
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 37/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
While loops are commonly used for counting a specific number of iterations, and for loops are
commonly used to iterate over all elements of a container. The range() function allows counting in for
loops as well. range() generates a sequence of integers between a starting integer that is included in
the range, an ending integer that is not included in the range, and an integer step value. The sequence
is generated by starting at the start integer and incrementing by the step value until the ending integer
©zyBooks 01/03/22 22:04 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
The range() function can take up to three integer arguments.
Ex: range(-7, -3) creates the sequence -7, -6, -5, -4.
range(X, Y, Z), where Z is positive, generates a sequence of all integers >= X and < Y,
incrementing by Z.
Ex: range(0, 50, 10) creates the sequence 0, 10, 20, 30, 40.
range(X, Y, Z), where Z is negative, generates a sequence of all integers <= X and > Y,
incrementing by Z.
range(0, 5, 2) 0 2 4 Bharathi
Every 2nd integer from 0Byreddy
to 4.
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 38/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Evaluating the range() function creates a new "range" type object. Ranges represent an arithmetic
progression, i.e., some sequence of integers with a start, end, and step between integers. The range
type is a sequence type like lists and tuples, but is immutable. In general, range objects are only used
as a part of a for loop statement.
LOUISVILLEMSBAPrep2DaviesWinter2022
Try changing the range() function to print every three years instead,
using the three-argument alternate version of range(). Modify the
interest calculation inside the loop to compute three years worth of
savings instead of one.
8
Load default template...
PARTICIPATION
ACTIVITY 5.6.1:
The range() function.
Bharathi Byreddy
01234567
LOUISVILLEMSBAPrep2DaviesWinter2022
123456
0123456
2345
01234
PARTICIPATION
ACTIVITY
5.6.2:
The range() function.
©zyBooks
Write the simplest range() function that generates the appropriate 01/03/22
sequence 22:04 1172417
of integers.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
1) Every integer from 0 to 500.
CHALLENGE
ACTIVITY 5.6.1:
Enter the for loop's output.
368708.2344834.qx3zqy7
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Type the program's output
for i in range(4):
0 1 2 3
1 2
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 40/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Check Next
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Both for loops and while loops can be used to count a specific number of loop iterations. A for loop
combined with range() is generally preferred over while loops, since for loops are less likely to become
stuck in an infinite loop situation. A programmer may easily forget to increment a while loop's variable
(causing an infinite loop), but for loops iterate over a finite number of elements in a container and are
thus guaranteed to complete.
PARTICIPATION
ACTIVITY 5.7.1:
While/for loop correspondence.
Animation captions:
As a general rule:
1. Use a for loop when the number of iterations is computable before entering the loop, as when
counting down from X to 0, printing a string N times, etc.
2. Use a for loop when accessing the elements of a container, as when adding 1 to every element
in a list, or printing the key of every entry in a dict, etc.
3. Use a while loop when the number of iterations is not computable before entering the loop, as
when iterating until a user enters a particular character.
These are not hard rules, just general guidelines. ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
5.7.2:
While loops and for loops.
Indicate whether a while loop or for loop should be used in the following scenarios:
while
for
Bharathi Byreddy
for LOUISVILLEMSBAPrep2DaviesWinter2022
3) Iterate 1500 times
while
for
Nested loops
A nested loop is a loop that appears as part of the body of another loop. The nested loops are
commonly referred to as the outer loop and inner loop.
Nested loops have various uses. One use is to generate all combinations of some items. Ex: The
following program generates all two letter .com Internet domain names. Recall that ord() converts a
1-character string into an integer, and chr() converts an integer into a character. Thus,
chr(ord('a') + 1) results in 'b'.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 42/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
"""
Two-letter domain
Program to print all 2-letter domain names.
names:
aa.com
ab.com
Note that ord() and chr() convert between text and the ASCII ac.com
or Unicode encoding:
ad.com
- ord('a') yields the encoded value of 'a', the number 97.
ae.com
- ord('a')+1 adds 1 to the encoded value of 'a', giving 98.
af.com
- chr(ord('a')+1) converts 98 back into a letter, producing ag.com
'b'
ah.com
"""
©zyBooks 01/03/22
ai.com22:04 1172417
aj.com
Bharathi Byreddy
aq.com
while letter2 <= 'z': # Inner loop
ar.com
print(f'{letter1}{letter2}.com')
as.com
letter2 = chr(ord(letter2) + 1)
at.com
letter1 = chr(ord(letter1) + 1)
au.com
av.com
aw.com
ax.com
ay.com
az.com
ba.com
bb.com
...
zy.com
zz.com
(Forget about buying a two-letter domain name: They are all taken, and each sells for several hundred
thousand or millions of dollars. Source: dnjournal.com, 2012.)
second while loop nested in the outer loop, but following theBharathi
first inner
Byreddy
1 '''
2 Program to print all 2-let
3 Note that ord() and chr()
4 ord('a') is 97. ord('b') i
5 '''
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 43/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
5 '''
6 print('Two-letter domain n
7
8 letter1 = 'a'
9 letter2 = '?'
10 while letter1 <= 'z': # O
11 letter2 = 'a'
12 while letter2 <= 'z':
13 print(f'{letter1}{
14 letter2 = chr(ord( ©zyBooks 01/03/22 22:04 1172417
16 LOUISVILLEMSBAPrep2DaviesWinter2022
17
Run the program below and observe the output. Modify the program to
print one asterisk per 5 units. So if the user enters 40, print 8 asterisks.
-1
1 num = 0
2 while num >= 0: Run
3 num = int(input('Enter a
4
5 if num >= 0:
6 print('Depicted grap
7 for i in range(num):
8 print('*', end='
9 print('\n')
10
11 print('Goodbye.')
12
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
5.8.1:
Nested loops.
body execute?
for i in range(2):
for j in range(3):
Bharathi Byreddy
for i in range(5):
print(f'{i}{j}')
c1 = 'a'
c2 = 'a'
print(f'{c1}{c2}', end
= ' ')
c2 = chr(ord(c2) + 1)
c1 = chr(ord(c1) + 1)
i1 = 1
i2 = 3
while i2 <= 9:
©zyBooks 01/03/22 22:04 1172417
end=' ')
LOUISVILLEMSBAPrep2DaviesWinter2022
i2 = i2 + 3
i1 = i1 + 10
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 45/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
CHALLENGE
ACTIVITY
5.8.1:
Nested loops.
368708.2344834.qx3zqy7
Start
©zyBooks 01/03/22
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
count = 0
for i in range(2):
2
for j in range(1):
count = count + 1
print(count)
1 2 3 4
Check Next
CHALLENGE
ACTIVITY 5.8.2:
Nested loops: Print rectangle
Given the number of rows and the number of columns, write nested loops to print a
rectangle.
* * *
* * *
368708.2344834.qx3zqy7
1 num_rows = int(input())
2 num_cols = int(input())
3
©zyBooks 01/03/22 22:04 1172417
5
LOUISVILLEMSBAPrep2DaviesWinter2022
6 print('*', end=' ')
7 print()
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 46/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Run
ACTIVITY 5.8.3:
Nested loops: Print seats. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Given num_rows and num_cols, print a list of all seats in a theater. Rows are numbered,
columns lettered, as in 1A or 3E. Print a space after each seat.
1A 1B 1C 2A 2B 2C
368708.2344834.qx3zqy7
1 num_rows = int(input())
2 num_cols = int(input())
3
4 # Note 1: You will need to declare more variables
5 # Note 2: Place end=' ' at the end of your print statement to separate seats by spac
6
7 ''' Your solution goes here '''
8
9 print()
Run
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Incremental programming
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 47/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
©zyBooks 01/03/22
Bharathi Byreddy
a complete version.
LOUISVILLEMSBAPrep2DaviesWinter2022
The following program allows the user to enter a phone number that includes letters, which appear on
phone keypads along with numbers and are commonly used by companies as a marketing tactic (e.g.,
1-555-HOLIDAY). The program then outputs the phone number using numbers only.
The first program version simply prints each element of the string to ensure the loop iterates properly
through each string element.
Element 0 is: 1
Element 1 is: -
Element 3 is: 5
Element 4 is: 5
index = 0
Element 5 is: -
index += 1
Element 8 is: L
Element 9 is: I
Element 10 is: D
Element 11 is: A
Element 12 is: Y
The second program version outputs the numbers (0 - 9) of the phone number and outputs a '?' for all
other characters. A FIXME comment attracts attention to code that needs to be fixed in the future.
©zyBooks 01/03/22 22:04 1172417
Many editors automatically highlight FIXME comments. Large projects with multiple
Bharathi programmers
Byreddy
Figure 5.9.2: Second version echoes numbers, and has FIXME comment.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 48/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Numbers only: 1?555????????
for character in user_input:
phone_number += character
else:
phone_number += '?'
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
print(f'Numbers only: {phone_number}')
The third version completes the elif branch for the letters A-C (lowercase and uppercase, per a
standard phone keypad). The code also modifies the if branch to echo a hyphen in addition to
numbers. The third version adds the elif branch for the letters A-C (lowercase and uppercase, per a
standard phone keypad).
Figure 5.9.3: Third version echoes hyphens too, and handles first three
letters.
phone_number = ''
phone_number += character
Enter phone number: 1-555-
elif ('a' <= character <= 'c') or ('A' <= HOLIDAY
else:
phone_number += '?'
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
The fourth version can be created by filling in the elif branches similarly for other letters and adding
more instructions for handling unexpected characters. The code is not shown below, but sample
input/output is provided.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 49/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
...
...
LOUISVILLEMSBAPrep2DaviesWinter2022
Enter phone number (letters/- OK, no spaces): 999-9999
...
1-555-HOLIDAY
Load default template...
1 user_input = input('Enter ph
2 phone_number = ''
Run
3
4 for character in user_input:
5 if ('0' <= character <=
6 phone_number += char
7 elif ('a' <= character <
8 phone_number += '2'
9 #FIXME: Add remaining el
10 else:
11 phone_number += '?'
12
13 print(f'Numbers only: {phone
14
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 5.9.1:
Incremental programming.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 50/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
True
False
Break statements
A break statement in a loop causes the loop to exit immediately. A break statement can sometimes
yield a loop that is easier to understand.
In the example below, the nested for loops generate possible meal options for the number of
empanadas and tacos that can be purchased. The inner loop body calculates the cost of the current
meal option. If the meal cost is equal to the user's amount of money, the search is over, so the break
statement immediately exits the inner loop. The outer loop body also checks if the meal cost and the
user's amount of money are equal, and if so, that break statement exits the outer loop.
The program could be written without break statements, but the loops' condition expressions would
be more complex and the program would require additional code, perhaps01/03/22
©zyBooks being harder to
22:04 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 51/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
empanada_cost = 3
taco_cost = 4
meal_cost = 0
LOUISVILLEMSBAPrep2DaviesWinter2022
meal_cost = (num_empanadas * empanada_cost) + (num_tacos * taco_cost)
if meal_cost == user_money:
break
if meal_cost == user_money:
break
if meal_cost == user_money:
else:
...
PARTICIPATION
ACTIVITY
5.10.1:
Break statements.
Given the following while loop, what is the value variable z is assigned with for the given
values of variables a, b and c?
©zyBooks 01/03/22 22:04 1172417
mult = 0
Bharathi Byreddy
if mult > c:
break
a = a + 1
z = a
1) a = 1, b = 1, c = 0
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 52/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
2) a = 4, b = 5, c = 20
LOUISVILLEMSBAPrep2DaviesWinter2022
Continue statements
A continue statement in a loop causes an immediate jump to the while or for loop header statement.
A continue statement can improve the readability of a loop. The example below extends the previous
meal finder program to find meal options for which the total number of items purchased is evenly
divisible by the number of diners. In addition, the following program will output all possible meal
options, instead of reporting the first meal option found.
The program uses two nested for loops to try all possible combinations of tacos and empanadas. If
the total number of tacos and empanadas is not exactly divisible by the number of diners (e.g.,
num_tacos + num_empanadas) % num_diners != 0, the continue statement will immediately
proceed to the next iteration of the for loop.
Break and continue statements can be helpful to avoid excessive indenting/nesting within a loop.
However, because someone reading a program could easily overlook a break or continue statement,
such statements should be used only when their use is clear to the reader.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 53/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
empanada_cost = 3
taco_cost = 4
©zyBooks 01/03/22 22:04 1172417
meal_cost = 0
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
num_options = 0
continue
if meal_cost == user_money:
num_options += 1
if num_options == 0:
...
PARTICIPATION
5.10.2:
Continue statements. ©zyBooks 01/03/22 22:04 1172417
ACTIVITY
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Given:
for i in range(5):
if i < 10:
continue
print(i)
output.
True
False
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
5.10.1:
Enter the output of break and continue.
368708.2344834.qx3zqy7
Start
Input
8
stop = int(input())
Output
result = 0
for n in range(10):
result += n * 2
0
print(n)
print(result) 2
12
1 2 3 4
Check Next
Bharathi Byreddy
CHALLENGE LOUISVILLEMSBAPrep2DaviesWinter2022
ACTIVITY
5.10.2:
Simon says.
"Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G,
B, Y) and the user must repeat the sequence. Create a for loop that compares each character
of the two strings. For each matching character, add one point to user_score. Upon a
mismatch, end the loop.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 55/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
User score: 4
368708.2344834.qx3zqy7
Bharathi Byreddy
1 user_score = 0 LOUISVILLEMSBAPrep2DaviesWinter2022
2 simon_pattern = input()
3 user_pattern = input()
4
5 ''' Your solution goes here '''
6
7 print('User score:', user_score)
Run
Bharathi
A loop may optionally include an else clause that executes only if the loop Byreddy
terminates
normally, not
LOUISVILLEMSBAPrep2DaviesWinter2022
using a break statement. Thus, the complete forms of while and for loops are:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 56/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
else:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
else:
The loop else construct executes if the loop completes normally. In the following example, a special
message "All names printed" is displayed if the entire list of names is completely iterated through.
Enter number of names to
num = int(input('Enter number of names to print: print: 2
Janice Clarice
'))
...
for i in range(len(names)):
Enter number of names to
if i == num:
©zyBooks
print: 8
01/03/22 22:04 1172417
break
BharathiMartin
Janice Clarice Byreddy
Veronica
print(names[i], end= ' ')
LOUISVILLEMSBAPrep2DaviesWinter2022
Jason
All names printed.
else:
DE 5 11 1 L l l Fi di l
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print lb b 57/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
zyDE 5.11.1: Loop else example: Finding a legal baby name.
The country of Denmark allows parents to pick from around 7,000
names for newborn infants. Names not on the list must receive special
approval from the Names Investigation Department of Copenhagen
University. (Surprisingly, many countries have naming laws, probably to
avoid names like "Brfxxccxxmnpcccclllmmnprxvclmnckssqlbb11116",
pronounced "Albin".)
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
Current
main.py arrow_drop_down Load default template...
file:
1 import edit_distance
2
3 #A few legal, acceptable Danish names
4 legal_names = ['Thor', 'Bjork', 'Bailey', 'Anders', 'Be
5 'Claus', 'Emil', 'Finn', 'Jakob', 'Karen', 'Julie',
6 'Bente', 'Eva', 'Helene', 'Ida', 'Inge', 'Susanne',
7 'Torben', 'Soren', 'Rune', 'Rasmus', 'Per', 'Michae
8 'Dorte'
9 ]
10
11 user_name = input('Enter desired name:\n')©zyBooks 01/03/22 22:04 1172417
13 LOUISVILLEMSBAPrep2DaviesWinter2022
print(f'{user_name} is an acceptable Danish name. C
14 else:
15 print(f'{user_name} is not acceptable.')
16 for name in legal_names:
17 if edit_distance.distance(name, user_name) < 2
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 58/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Bjork
Run
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 5.11.1:
Loop else.
x = 0
y = 5
z = ?
while x < y:
if x == z:
print('x == z')
break
x += 1
else:
print('x == y')
CHALLENGE
ACTIVITY 5.11.1:
Loop else.
Bharathi Byreddy
Start LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 59/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
result = 0
n = 2
while n < 5:
result -= 4
n += 1
else:
print(f'/ {result}')
print('done')
1 2 3
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Check Next
A programmer commonly requires both the current position index and corresponding element value
when iterating over a sequence. The example below demonstrates how using a for loop with range()
and len() to iterate over a sequence generates a position index but requires extra code to retrieve a
value.
©zyBooks 01/03/22 22:04 1172417
Element 0: 4
Element 1: 8
LOUISVILLEMSBAPrep2DaviesWinter2022
value = origins[index] # Retrieve value of element in list.
Element 2: 10
print(f'Element {index}: {value}')
Similarly, a for loop that iterates over a container obtains the value directly, but must look up the index
with a function call.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 60/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Element 0: 4
LOUISVILLEMSBAPrep2DaviesWinter2022
The enumerate() function retrieves both the index and corresponding element value at the same time,
providing a cleaner and more readable solution.
Element 0: 4
The enumerate() function yields a new tuple each iteration of the loop, with the tuple containing the
current index and corresponding element value. In the example above, the for loop unpacks the tuple
yielded by each iteration of enumerate(origins) into two new variables: "index" and "value".
Unpacking is a process that performs multiple assignments at once, binding comma-separated
names on the left to the elements of a sequence on the right. Ex: num1, num2 = [350, 400] is
equivalent to the statements num1 = 350 and num2 = 400.
PARTICIPATION
ACTIVITY
5.12.1:
enumerate().
print(index, value)
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
1) If my_list = ['Greek', 'Nordic',
'Mayan'], what is the output of the
program?
Greek
Nordic
Mayan
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 61/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
0 Greek
1 Nordic
2 Mayan
1 Greek
2 Nordic
3 Mayan
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
CHALLENGE LOUISVILLEMSBAPrep2DaviesWinter2022
ACTIVITY 5.12.1:
Using enumerate in for loops.
368708.2344834.qx3zqy7
Start
print(season, position)
1 2
Check Next
The following is a sample programming lab activity; not all classes using a zyBook require students to
fully complete this activity. No auto-checking is performed. Users planning to fully complete this
©zyBooks 01/03/22 22:04 1172417
program may consider first developing their code in a separate programming environment.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Analyzing dice rolls is a common example in understanding probability and statistics. The following
program calculates the number of times the sum of two dice (randomly rolled) is equal to six or seven.
1 import random
2
3 num_sixes = 0
4 num_sevens = 0 Run
5 num_rolls = int(input('En
6
7 if num_rolls >= 1:
8 for i in range(num_ro ©zyBooks 01/03/22 22:04 1172417
1. Calculates the number of times the sum of the randomly rolled dice equals each possible value
from 2 to 12.
2. Repeatedly asks the user for the number of times to roll the dice, quitting only when the user-
entered number is less than 1. Hint: Use a while loop that will execute as long as num_rolls is
greater than 1.
3. Prints a histogram in which the total number of times the dice rolls equals each possible value is
displayed by printing a character, such as *, that number of times. The following provides an
example:
2s: **
3s: ****
4s: ***
5s: ********
6s: *************
7s: *****************
8s: *************
9s: *********
10s: **********
11s: *****
12s: **
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 63/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to
output a right triangle that instead uses the user-specified triangle_char character. (1 pt)
(2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line
will have one user-specified character, such as % or *. Each subsequent line will have one additional
user-specified character until the number in the triangle's base reaches triangle_height. Output a
©zyBooks 01/03/22 22:04 1172417
Enter a character:
%
% %
% % %
% % % %
% % % % %
NaN.2344834.qx3zqy7
LAB
ACTIVITY 5.14.1:
LAB: Warm up: Drawing a right triangle 0/3
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 64/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Develop mode Submit mode Run your program as often as you'd like, before submitting
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
trending_flat trending_flat
LOUISVILLEMSBAPrep2DaviesWinter2022
main.py
Run program Input (from above) Outp
(Your program)
History of your effort will appear here once you begin working
on this zyLab.
-15
10
-15 -10 -5 0 5 10
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
20
5
For coding simplicity, output a space after every integer, including the last.
NaN.2344834.qx3zqy7
LAB
ACTIVITY
5.15.1:
LAB: Output range with increment of 5 0 / 10
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
main.py Load default template...
trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)
LOUISVILLEMSBAPrep2DaviesWinter2022
History of your effort will appear here once you begin working
on this zyLab.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 66/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Write a program that reads a list of integers into a list as long as the integers areByreddy
Bharathi greater
than zero,
then outputs the smallest and largest integers in the list. LOUISVILLEMSBAPrep2DaviesWinter2022
10
5
21
2
-6
2 and 21
You can assume that the list of integers will have at least 2 values.
NaN.2344834.qx3zqy7
LAB
ACTIVITY
5.16.1:
LAB: Smallest and largest numbers in a list 0 / 10
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 67/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
trending_flat trending_flat
LOUISVILLEMSBAPrep2DaviesWinter2022
main.py
Run program Input (from above) Outp
(Your program)
History of your effort will appear here once you begin working
on this zyLab.
60 Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
140
200
75
100
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 68/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
50,60,75,
The 5 indicates that there are five integers in the list, namely 50, 60, 140, 200, and 75. The 100
indicates that the program should output all integers less than or equal to 100, so the program
outputs 50, 60, and 75.
For coding simplicity, follow every output value by a comma, including the last one.
©zyBooks 01/03/22 22:04 1172417
Such functionality is common on sites like Amazon, where a user can filter results.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
NaN.2344834.qx3zqy7
LAB
ACTIVITY 5.17.1:
LAB: Output values in a list below a user defined amount 0 / 10
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 69/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
History of your effort will appear here once you begin working
on this zyLab.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
For this program, adjust the values by dividing all values by the largest value. The input begins with an
integer indicating the number of floating-point values that follow.
Output each floating-point value with two digits after the decimal point, which can be achieved as
follows:
print(f'{your_value:.2f}')
30.0
50.0
10.0
100.0
65.0
0.30
0.50
0.10
1.00
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
0.65
LOUISVILLEMSBAPrep2DaviesWinter2022
The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and
65.0. 100.0 is the largest value in the list, so each value is divided by 100.0.
NaN.2344834.qx3zqy7
LAB
5 18 1: LAB: Adjust values in a list by normalizing
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 70/71
1/3/22, 10:07 PM MSBA Prep 2: Python Prep home
ACTIVITY
5.18.1:
LAB: Adjust values in a list by normalizing
0 / 10
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/5/print 71/71