Python - 5. Iterations (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
A5.4 Counting in a range with a while Loop
A5.8 Tracking inner and outer loops
Project 5.3: Choice of Two Games
5. Loops
5.1 while Loops (A5.1 - A5.4)
- A repetition statement (or loop) lets us execute a statement as many times as we need to. A while statement is a loop that evaluates a boolean condition (True or False), just like an if statement does, and executes a chunk of code if the condition is True. If the condition is False, the loop is exited and the program continues after it.
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.
- A variable called counter is set to 1. This is our iteration variable.
- The while loop is entered:
- Is counter less than or equal to 10? Yes, it is 1.
- The statements within the loop are executed:
- counter is printed (1 is printed to the screen)
- counter is incremented (increased) by 1 and is now 2.
- The end of the loop is reached and the condition at the top is evaluated again.
- Is counter less than or equal to 10? Yes, it is 2.
- The statements within the loop are executed:
- counter is printed (2 is printed to the screen)
- counter is incremented (increased) by 1 and is now 3.
- The end of the loop is reached and the condition at the top is evaluated again.
- (this continues until 10 is printed to the screen and the value of counter is now 11.)
- Is counter less than or equal to 10? No, it is 11. The loop is exited by skipping the loop block and the program continues.
- The print statement is executed and prints: All done counting!
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
- Some loops never end. These are called infinite loops and can crash the computer. If we change Example #2 to add 2 every time instead of subtracting, number will always be greater than 1 and the loop will never end.
Example #3:
number = 6
while number > 1:
print(number)
number = number + 2
print("The value of number: " + str(number))
5.3 The break Statement
- You can use the break command to exit any loop. When the program hits break, it immediately exits the loop and continues with the program.
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
- The continue keyword says to stop the current iteration (pass through the loop) and move back to the top of the loop.
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
- The while statement is good to use when you don’t know how many times you want to execute the loop body, such as the repeated play of a game. In that case, you don’t know how many times the user will want to play and the loop keeps going until they decide that they are done. These are indefinite loops.
- The for statement is a repetition statement that works well when you know how many times you want to execute the loop or you have a defined (or definite) set of numbers or strings that you will work through. These are definite loops.
- for loops can be used to move through things such as the characters in a string or the lines of a file.
- for and in are keywords and we can choose our own iteration variable. i, j, k and n are common choices, but more descriptive names should be chosen.
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
- The for loop is efficient and easy to use because it:
- Manages the iteration variable for us
- Understands where to end the loop
- Saves a lot of work vs the while loop
- Handles everything in a single line of code
- Notice the in keyword. It is used to set the iteration variable to each value IN the set of values to work through.
5.6 The range() Function (A5.5 - A5.7)
- Sometimes, especially with numbers, we don’t want to list all of the values for a for loop to move through. The range() function allows us to set a range of numbers easily. It is a built-in function (already defined for us and ready to go) and can be used three ways:
- range(stop) - Takes one argument.
- range(start, stop) - Takes two arguments.
- range(start, stop, step) - Takes three arguments.
Parameter descriptions:
- stop - This parameter is required. It is an integer specifying at which number to stop (it is not included).
- start - This is an optional parameter. It is an integer specifying at which position to start. When a start value is not included, the default is 0.
- step - This is an optional parameter. It is an integer specifying the incrementation (also known as a step). When a step value is not included, the default is 1.
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)
- Loops can have loops in them. Typically, each time the outer loop (first loop) increments, the inner loop runs in its entirety.
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)
- This is not directly related to loops, but we want to be able to generate random numbers to make some simple games, so we are going to import the random module. What does this mean? Start from what we know...
5.8.1 What are functions and modules?
Function review:
- Overview:
- Let’s start with a review of functions. Functions are a handy way to isolate a particular part of your program's functionality and make it reusable. We learned about that last chapter.
- Built-in functions:
- We can make our own functions, or we can use built in functions like print(), int() and type(). These are functions that are always available and ready for use. Here is a LIST of the built-in functions in Python.
Modules:
- Overview:
- Modules are a way to collect a number of related functions in one file, which you can then use in multiple projects and share with other programmers.
- Modules are saved in a file with a .py extension
- The beauty of having a programming language with a large community is that people are constantly adding to the library of things that Python can do.
- Built-in modules:
- There are a bunch of built-in modules found HERE which you can easily use in your program. This is known as the Python standard library. No downloading is required to access these. Adding them to your programs is outlined in the section below.
- Modules that are not built-in: (not dealing with this yet, but great to know)
- There are many more modules that are not included (not built-in) with the Python standard library. They need to be downloaded from the command line using pip. pip (Pip Installs Packages) is the main package manager for Python. A package is how a group of modules are stored. These packages are published to the Python Package Index, also known as PyPI (pronounced Pie-Pea-Eye) found HERE. More detailed information on modules and packages is found HERE.
5.8.2 Importing built-in modules to your program
- There are three main commands when adding modules to your Python code: import, from, and as. import is the only one that is required. The other two are optional depending on the circumstances.
Using just import:
- We’ll start with the simplest command, importing an entire module. Just the command import and the module name
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:
- To be more specific, we can import the functions we will use. We use the from command to specify our module, then the import command to explicitly list the components we need:
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:
- We can also simplify how we reference (what we call) the function. We use the as command for that. We can import something and name it whatever we want. Just follow the import command with as and specify the new name.
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
- The randint() function is used to generate random integers. This function takes two parameters which are the low end and high end of the range of numbers. Both the high and low numbers are included in those generated.
- These are all acceptable ways to generate a number from 1 to 100 inclusively. We need to import and use the randint() function which is part of the built-in random module:
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:
- The Slot Machine game (turn the entire program into a function)
- The Guessing game (turn the entire program into a function)
- 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?
………….