Nested Loops

Nested Loops

A nested loop is just a loop inside the body of another loop.

A Simple Case

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!")

Cheers!

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

Some Questions to Ask…

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

Some Pseudocode

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!"
"""

A Cheers Implementation

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!')

Password Generator

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

Password Generator

Create a program that generates passwords! The passwords only consist of digits, though…

Password Generator Solution

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)

Triangle

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:

"""
*
**
***
****
*****
"""

Potential Solution for Triangle

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