← All chapters

Python curriculum / Chapter 05

Loops

while and for loops, range, nesting, modules, assignments, and three complete projects.

Python - 5. Iterations (loops)

5. Loops

5.1 while Loops (A5.1 - A5.4)

5.2 Infinite Loops

5.3 The break Statement

5.4 The continue Statement

5.5 for Loops

5.6 The range() Function (A5.5 - A5.7)

5.7 Nested Loops (A5.8 - A5.10)

5.8 Importing Modules (Projects 5.1, 5.2, 5.3)

5.8.1 What are functions and modules?

5.8.2 Importing built-in modules to your program

5.8.3 Generate a random integer

Chapter 5: Assignments

A5.1 Count to 1000

A5.2 Count by 2’s

A5.3 Counting across and down

A5.4 Counting in a range with a while Loop

A5.5 Count to 50

A5.6 Count to 210

A5.7 Line of stars

A5.8 Tracking inner and outer loops

A5.9 Nested Loop Stars

A5.10 Multiplication Table

Projects

Project 5.1: Guessing Game

Project 5.2: Slot Machine

Project 5.3: Choice of Two Games

5. Loops

5.1 while Loops (A5.1 - A5.4)

Example #1:

counter = 1

while counter <= 10:

print(counter)

counter = counter + 1

print("All done counting!")

OUTPUT:

1

2

3

4

5

6

7

8

9

10

All done counting!

Let’s walk through this program.

Example #2:

number = 6

while number > 1:

print(number)

number = number - 2

print("The value of number: " + str(number))

OUTPUT:

6

4

2

The value of number: 0

Make sure you walk through this program and understand how it is working. number is our iteration variable. Here we are counting down instead of up like the first example.


5.2 Infinite Loops

Example #3:

number = 6

while number > 1:

print(number)

number = number + 2

print("The value of number: " + str(number))

5.3 The break Statement

Example #4:

number = 1

while number < 10:

print(number)

number = number + 1

if number > 5:

break

print("You are out of the loop!!")

OUTPUT:

1

2

3

4

5

You are out of the loop!!

In this example, the loop looks like it will print from 1 to 9, but the if statement becomes true once number is greater than 5. This triggers the break which exits the loop.

5.4 The continue Statement

Example #5:

number = 1

while number < 10:

number = number + 1

if number % 2 == 0: # True when number is even

continue

print(number)

print("You are out of the loop!!")

OUTPUT:

3

5

7

9

You are out of the loop!!

Here, the iteration variable number is incremented at the beginning of the while loop. The if statement is true for even numbers, which triggers the continue statement. This means that it will jump back to the top of the while loop for each even number and start the loop again. This way, only odd numbers are printed.

5.5 for Loops

Example #6: Counter up to 5

for i in [1, 2, 3, 4, 5]: # The numbers in the square brackets are

print(str(i)) # known as a list.

print("Done")

OUTPUT: 1

2

3

4

5

Done

  • This can also be done with strings:

Example #7: Looping through a list of strings

for name in [‘Amir’, ‘Nelly’, ‘Kamala’, ‘Steve’]

print(name)

OUTPUT:

Amir

Nelly

Kamala

Steve

The iteration variable starts at Amir and moves its way through the list

each time the for loop is repeated.

Example #8: Another way to handle Example #4

friends = [‘Amir’, ‘Nelly’, ‘Kamala’, ‘Steve’]

for name in friends:

print(name)

OUTPUT:

Amir

Nelly

Kamala

Steve

5.6 The range() Function (A5.5 - A5.7)

  1. range(stop) - Takes one argument.
  2. range(start, stop) - Takes two arguments.
  3. range(start, stop, step) - Takes three arguments.

Parameter descriptions:

Example #9: Create a sequence of numbers from 0 to 5, and print each item in the sequence

for n in range(6): # One parameter. 6 is not included.

print(n)

OUTPUT: 0

1

2

3

4

5

Example #10: Create a sequence of numbers from 3 to 5, and print each item in

the sequence

for n in range(3, 6):

print(n)

OUTPUT: 3

4

5

Example #11: Create a sequence of numbers from 3 to 13, and increment (step)

by 2 instead of 1:

for n in range(3, 14, 2):

print(n)

OUTPUT: 3

5

7

9

11

13

5.7 Nested Loops (A5.8 - A5.10)

Example #12: This program builds the numbers from 0 to 99 with i as the tens counter and j as the ones counter.

for i in range(10): # Outer loop counting the tens

for j in range(10): # Inner loop counting the ones

print('Counting: ' + str(i) + str(j))

OUTPUT: Counting: 00

Counting: 01

Counting: 02

……

Counting: 98

Counting: 99

5.8 Importing Modules (Projects 5.1, 5.2, 5.3)

5.8.1 What are functions and modules?

Function review:

Modules:

5.8.2 Importing built-in modules to your program

Using just import:

Example #13:

import math # The math module is imported

print(math.ceil(3.4)) # The ceil function of the math module is used

(rounds up)

print(math.floor(3.4)) # The floor function of the math module is used

(rounds down)

Now, while this command is very straightforward, it isn’t very efficient. First, we are importing the entire module and may only need a little bit of it. Also, we need to use it before each function that we are calling, like math.ceil().

Using from with import:

Example #14:

from math import ceil, floor # Import just the two functions we need

print(ceil(3.4)) # Use the function without the module name

print(floor(3.4))

Using from, import and renaming the module with as:

Example #15:

from datetime import datetime as dt # we can now refer to datetime as dt

print(dt.now()) # 2020-03-29 01:43:03.170480

5.8.3 Generate a random integer

Example #16: import random

print(random.randint(1, 100))

Example #17: from random import randint

print(randint(1, 100))

Example #18: from random import randint as rnd # I made up rnd

print(rnd(1,100))

Chapter 5: Assignments

A5.1 Count to 1000

Create a program that counts from 100 to 1000 by 100’s and says “Finished!!” at the end.

PROGRAM STRUCTURE:

# Declare and initialize a variable with a value of 100

#while (condition for variable being less than or equal to 1000)

# print value of variable

# increase value of variable by 100

# Print: Finished!

OUTPUT:

100

200

300

400

500

600

700

800

900

1000

Finished!

A5.2 Count by 2’s

Create a program using a while loop that prints out all even numbers from 1 to 50.

PROGRAM STRUCTURE:

# Declare and initialize a variable with a value of 1

#while (condition for variable being less than or equal to 50)

# Create an if statement to test if the counter is even. If it is, print that

# number. (HINT: Use the modulus operator)

# Outside the if statement, increase the value of the variable by 1

# Print: There are your even numbers!

OUTPUT: (not entirely shown)

2

4

6

8

…….

46

48

50

There are your even numbers!

A5.3 Counting across and down

Write a program that counts to 100. The output should be in rows of 5 numbers as shown in the output.

PROGRAM STRUCTURE:

# Declare and initialize a variable with a value of 1

#while (condition for the variable being less than or equal to 100)

# Work with tabs and newlines for proper formatting.

# Increment the value of the variable by 1.

#

# Hint #1: Use an if that checks for numbers that are divisible by 5.

# Modulus is helpful here.

#

# Hint #2: You can print on the same line by changing the print statement

# to look like this: print(variable, end=’\t ‘). This would finish

# the print statement with a tab instead of a new line.

OUTPUT: (not entirely shown)

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

……

96 97 98 99 100

A5.4 Counting in a range with a while Loop

Ask the user for two numbers. Determine which is the higher and lower number. Use a function to count down from the higher number to the lower number using a while loop.

PROGRAM STRUCTURE:

# Create a function that takes in a high number and a low number and

# prints all of the numbers from the high one to the low one using a while loop

# Request two numbers from the user.

# Determine which number is higher (using if statements) and call the function

# that you built above, making sure the high and low numbers are assigned

# appropriately.

SAMPLE RUN #1:

Please give me a number between 1 and 100:

30

Please give me another number between 1 and 100:

41

41 40 39 38 37 36 35 34 33 32 31 30

SAMPLE RUN #2:

Please give me a number between 1 and 100:

50

Please give me another number between 1 and 100:

40

50 49 48 47 46 45 44 43 42 41 40

A5.5 Count to 50

Use a for loop to count from 1 to 50 on the screen.

OUTPUT:

1

2

3

……

49

50

A5.6 Count to 210

Use a for loop to count from 3 to 210 by 3’s.

OUTPUT:

3

6

9

…..

207

210

A5.7 Line of stars

Ask the user for a number and then print that many stars on one line.

SAMPLE RUN #1:

How many stars would you like to print?

7

*******

SAMPLE RUN #2:

How many stars would you like to print?

20

********************

A5.8 Tracking inner and outer loops

Create a program with nested loops that lists the value of the counter in each loop. i is the outer loop and j is the inner loop. The program will look similar to Example #12. Make sure you match the output exactly. Include the blank line when i changes value.

OUTPUT:

i = 1 j = 1

i = 1 j = 2

i = 1 j = 3

i = 2 j = 1

i = 2 j = 2

i = 2 j = 3

i = 3 j = 1

i = 3 j = 2

i = 3 j = 3

A5.9 Nested Loop Stars

Use nested loops to create the star pattern below. The outer loop counts the number of rows and the inner loop prints the stars in each row. (Hint: In row one, there is one star. In row two, there are two stars….)

PROGRAM STRUCTURE:

for row in ########: # Fill in the blank. Keeps count of row number

for stars in ########: # Hint: related to the row number

print('*', end = ' ') # This is how you print something without

going to a new line.

# You need a fourth line to make this work.

OUTPUT:

*

**

***

****

*****

A5.10 Multiplication Table

Use a nested loop to create a multiplication table from 1 to 6. Hint: Use the escape character \t for a nice layout. HINT: The print statement will involve both iteration variables.

OUTPUT:

1 2 3 4 5 6

2 4 6 8 10 12

3 6 9 12 15 18

4 8 12 16 20 24

5 10 15 20 25 30

6 12 18 24 30 36

Projects

Project 5.1: Guessing Game

Create a program that generates a random number from 1 to 100. It will then ask the player to guess the number. As the player guesses, they should be informed if they need to guess higher or lower. If they get the number, they should be told that they are correct and asked if they want to play the game again. If the answer is yes, the game should begin again.

SAMPLE OUTPUT:

I have a number between 1 and 100. Please guess the number:

8

Guess higher:

45

Guess lower:

33

YOU GOT IT!

Would you like to play again? (1 - Yes, 2 - No)

1

I have a number between 1 and 100. Please guess the number:

…...

Would you like to play again? (1 - Yes, 2 - No)

2

Thanks for playing!

Project 5.2: Slot Machine

Create a program that acts like a slot machine. You start with $10 and each play is $1. The program should generate three random numbers from 1 through 9. If two of the numbers match, you get $3 back. If all three numbers match, you get $10 back. Be sure to give the player a running balance of how much money they have.

SAMPLE OUTPUT:

You have $10.

Press “p” to play the slots! p

2 9 2

You won $3!

You now have $12.

Press “p” to play the slots! p

1 8 3

You didn’t match any numbers.

You now have $11.

Press “p” to play the slots! p

7 7 7

Woohoo! You won $10!

You now have $20.

Press “p” to play the slots! p

……..

Project 5.3: Choice of Two Games

HEADS-UP: If this doesn’t make sense, have Mr. Finkel walk you through it.

This project will combine the two games written in Project 5.1 and Project 5.2. They will each become modules which will be imported and called from the main program. To do this you will have three files:

  1. The Slot Machine game (turn the entire program into a function)
  2. The Guessing game (turn the entire program into a function)
  3. The main Game Play file that will call the other two

When the program runs, the user will have the choice of which game to play. Once that game is finished, they will be sent back to the original menu with the offer to play either game.

BASIC EXAMPLE:

File #1: Game1.py

def Game1():

print("this is game #1!")

File #2: Game2.py

def Game2():

print("this is game #2!")

File #3: PlayGames.py

import Game1, Game2

choice = input('Would you like to play game #1 or game #2? ')

if choice == 1:

Game1.Game1()

else:

Game2.Game2()

Sample Run:

Would you like to play game #1 or game #2? 1

this is game #2!

SAMPLE RUN FOR ASSIGNMENT:

Would you like to play 1) Guess a number or 2) slots?

2

Welcome to SLOTS!!

You have $10.

Press “p” to play the slots, “q” to quit:

p

1 3 5

You didn’t match any numbers.

You now have $9.

Press “p” to play the slots, “q” to quit:

q

Would you like to play 1) Guess a number or 2) slots?

1

Welcome to GUESS A NUMBER!!

I have a number between 1 and 100. Please guess the number:

45

Guess higher:

91

Guess lower:

54

YOU GOT IT!

Would you like to play 1) Guess a number or 2) slots?

………….