This lab is intended to give you a taste of how iteration works. Pieces of this lab are based on problems written by Dominique Thiebaut at Smith College, and it was adapted for this course in June 2018 by R. Jordan Crouser.
for...in
) loopsA definite loop is a loop where you know exactly how many times the loop is going to run before you start.
In Lab 1: Introduction to Python, we wrote a loop that looked like this:
for name in [ "Aleah", "Belle", "Chen" ]:
print(name)
Without even typing the code into the console
, we can tell that the code inside the loop is going to execute
exactly 3 times:
"Aleah"
"Belle"
"Chen"
We could also write a loop that iterates over list of numbers:
for x in [ 1, 2, 3, 4, 5 ]:
print(x)
Looking at the list above, we can tell that the look is going to execute five times (once for each element in the list).
range()
functionThe range()
function provides a quick way to generate a list of numbers in Python. This is particularly useful when we want to loop a set number of times, or over a list of numbers that have a particular pattern (but we don’t want to type them manually).
range()
function worksTry running the loops below in the Python shell. Feel free to play around with the numbers, and see if you can get a feel for how range()
works:
# Loop 1: range() with one value
for n in range( 10 ):
print(n)
# Loop 2: range() with 2 values
for n in range( 5, 10 ):
print(n)
# Loop 3: range() with 2 values, starting at a negative value
for n in range( -1, 4 ):
print(n)
# Loop 4: range() with 3 values
for n in range( 1, 10, 2 ):
print(n)
# Loop 5: range() with 3 values, last value negative
for n in range( 10, 0, -2 ):
print(n)
range()
Now, your turn:
Create a section header using a comment:
# Challenge #1: Range-Controlled Loops
Even numbers:
Write a loop that prints all the even numbers between 0 and 20.
Multiples of 3:
Write a loop that prints all the multiples of 3 between -20 and 20.
counter
Let’s start with a simple list-controlled loop:
for animal in [ "dog", "cat", "horse", "chicken" ]:
print(animal)
Now imagine we wanted to count the number of times we have gone through the loop. We can do this by defining a variable
and incrementing its value each time the loop runs:
# Initialize the counter to 0
counter = 0
# Run through the loop
for animal in [ "dog", "cat", "horse", "chicken" ]:
counter = counter + 1 # +1 each time the loop runs
# Print out the (updated) value of counter
print("The loop ran", counter, "times.")
Run the program. What do you notice?
Create a section header using a comment:
# Challenge #2: Counting in Loops
Modify the program to print
the value of counter
as well as the animal
, so that its output looks something like this:
Animal 1: dog
Animal 2: cat
Animal 3: horse
Animal 4: chicken
while
) loopsIn addition to for
loops (where we know in advance exactly how many times we’re going to repeat), sometimes it is helpful to be able to loop until some condition is met.
For example, the following code prints out all positive square numbers less than 200:
n = 1
while(n**2 < 200):
print(n, "*", n, "=", n**2)
n+=1 # increment n
These kinds of loops (called indefinite loops) are frequently used in combination with user input, because we don’t know in advance how many times the user will need the code to repeat. For example, here is a simple guessing game:
import random
secret_number = random.randint(0,9)
user_guess = eval(input("Guess an integer between 0 and 9: "))
# Keep looping until they guess correctly
while user_guess != secret_number:
print("Nope! Try again...")
user_guess = eval(input("Guess an integer between 0 and 9: "))
print("CONGRATS! The secret number was", secret_number)
Note that each time the code runs, the call to random.randint(0,9)
selects a different integer between 0 and 9. Try running it multiple times to see it in action!
In this challenge, you’ll write a python program that asks the user to enter a name, email address and phone number, and then outputs it back on the screen. If desired, the program then repeats the process.
Create a section header using a comment:
# Challenge 3: Contact Information
input()
function to collect the user’s first name, last name, email address, and age.Repeat this process until the user enters NO
, then print Goodbye!
Here is an example of what your program might look like when it is run:
First name: **Allie**
Last name: **Gator**
Email address: **allie@gator.com**
Phone: **222-222-2222**
+-------------------------+
| Name: Allie Gator |
| Number: 222-222-2222 |
| Email: allie@gator.com |
+-------------------------+
Enter another contact (YES/NO)? **YES***
First name: **Croc**
Last name: **O'Dile**
Email address: **smile@lots-of-teeth.com**
Phone: **123-456-7890**
+---------------------------------+
| Name: Croc O'Dile |
| Number: 123-456-7890 |
| Email: smile@lots-of-teeth.com |
+---------------------------------+
Enter another contact (YES/NO)? **NO**
Goodbye!
Note: the information entered by the user is surrounded by **asterisks** just to highlight it - your user does not need to enter them.
“Old MacDonald’s Farm” is a song most American kids learn at one point in their life. If you don’t know it, this YouTube video will get you acquainted with it. :-)
The goal of this problem is for you print
the lyrics to the famous song using a for loop
on a list of animal:sound
pairs provided by the user. To do this, you’ll need to bring together your knowledge of user input, loops and string operations.
Create a section header using a comment:
# Final Challenge: Old MacDonald's Farm
Ask the user to enter a set of animal:sound
pairs (separated by commas) using the input()
function. Their input might look something like this:
Enter a set of animal:sound pairs (separated by spaces): **dog:woof cat:meow horse:neigh chicken:cluck**
Note: again, user input is surrounded by **asterisks** for emphasis only.
Separate the input string
into a list of strings containing animal:sound
pairs.
Separate each animal:sound
pair into an animal
and a sound
(hint: the .split()
method can take a parameter specifying which character to use for the split).
Finally, print the lyrics of “Old MacDonald” using the user input. Your goal is output that looks like this:
Verse 1 - DOG
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a dog, E-I-E-I-O
With a woof woof here and a woof woof there
Here a woof, there a woof, everywhere a woof woof!
Old MacDonald had a farm, E-I-E-I-O
Verse 2 - CAT
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a cat, E-I-E-I-O
With a meow meow here and a meow meow there
Here a meow, there a meow, everywhere a meow meow!
Old MacDonald had a farm, E-I-E-I-O
Verse 3 - HORSE
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a horse, E-I-E-I-O
With a neigh neigh here and a neigh neigh there
Here a neigh, there a neigh, everywhere a neigh neigh!
Old MacDonald had a farm, E-I-E-I-O
Verse 4 - CHICKEN
Old MacDonald had a farm, E-I-E-I-O
And on his farm he had a chicken, E-I-E-I-O
With a cluck cluck here and a cluck cluck there
Here a cluck, there a cluck, everywhere a cluck cluck!
Old MacDonald had a farm, E-I-E-I-O
lab4.py
file via Moodle.