A nested loop is just a loop inside the body of another loop.
How many times does the outer loop run? For each run of the outer loop, how many times does the inner loop run? How many times is "You're driving me loopy!" printed out? →
for i in range(5):
print('Run number: %s' %(i))
for j in range(10):
print("You're driving me loopy!")
Write a program that asks for how many cheers, and then prints out the appropriate number of cheers.
How many cheers shall we give?
> 2
Cheer #1: Hip hip hooray!
Cheer #2: Hip hip hooray!
How many cheers shall we give?
> 1
Cheer #1: Hip hip hooray!
How many cheers shall we give?
> 0
Based on this output… What parts are repeated and what kind of loops would you use for each part? →
How many cheers shall we give?
> 2
Cheer #1: Hip hip hooray!
Cheer #2: Hip hip hooray!
How many cheers shall we give?
> 1
Cheer #1: Hip hip hooray!
How many cheers shall we give?
> 0
In pseudocode, how might we describe this program?
"""
assume number of cheers is not zero
as long as the number of cheers isn't zero
ask for number of cheers
for every cheer
display the number and display "Hip hip hooray!"
"""
Using the output we've seen, implement the cheers program. →
How many cheers shall we give?
> 2
Cheer #1: Hip hip hooray!
Cheer #2: Hip hip hooray!
How many cheers shall we give?
> 0
number_of_cheers = 1
while number_of_cheers > 0:
number_of_cheers = int(input('How many cheers shall we give?\n> '))
for num in range(1, number_of_cheers + 1):
print('Cheer #' + str(num) + ': Hip hip hooray!')
Below is the output of a program that generates passwords based on a number that is input by the user. It's similar to the cheers example.
Please enter a pasword length (0 to exit)
>10
2402991612
Please enter a pasword length (0 to exit)
>5
60773
Please enter a pasword length (0 to exit)
>2
72
Please enter a pasword length (0 to exit)
>0
Create a program that generates passwords! The passwords only consist of digits, though…
import random
password_length = 1
while password_length != 0:
password_length = int(input('Please enter a pasword length (0 to exit)\n>'))
password = ''
for i in range(password_length):
password += str(random.randint(0, 9))
print(password)
Draw a triangle made of stars by using nested loops to accumulate single characters. Don't use string multiplication or string formatting. Here's the expected output:
"""
*
**
***
****
*****
"""
# create an empty string to hold the triangle
triangle = ''
for row in range(1, 6):
# create a string to hold the current row
row_of_stars = ''
# keep on adding stars based on the current row
for col in range(row):
row_of_stars += '*'
# add the row to the triangle with a new line
triangle += row_of_stars + '\n'
print(triangle)