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.

Definite (for...in) loops

A definite loop is a loop where you know exactly how many times the loop is going to run before you start.

A familiar example

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:

  • once for "Aleah"
  • a second time for "Belle"
  • and a third time for "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).

Using the range() function

The 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).

How the range() function works

  • If you give it 1 number, it will generate a series of integers starting at 0 and going up to (but not including) that number.
  • If you give it 2 numbers, generate a series of integers starting at the first number and going up to (but not including) the second number.
  • If you give it 3 numbers, the third number specifies how big each “step” should be (can be positive or negative).

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

Challenge #1: Definite Loops Using range()

Now, your turn:

  1. Create a section header using a comment:

    # Challenge #1: Range-Controlled Loops
  2. Even numbers:
    Write a loop that prints all the even numbers between 0 and 20.

  3. Multiples of 3:
    Write a loop that prints all the multiples of 3 between -20 and 20.

  4. List odd numbers in reverse order:
    Write a loop that prints all the odd numbers starting at 9 and going down to (and including) 1.

Adding a 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?

Challenge #2: Counting in Loops

  1. Create a section header using a comment:

    # Challenge #2: Counting in Loops
  2. 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

Indefinite (while) loops

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

Challenge #3: Contact Information

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.

  1. Create a section header using a comment:

    # Challenge 3: Contact Information
  2. Use the input() function to collect the user’s first name, last name, email address, and age.
  3. Print a nicely-formatted “information card” using the user-supplied data.
  4. Ask if the user would like to enter another contact.
  5. 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.

Final Challenge: Old MacDonald’s Farm

“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.

  1. Create a section header using a comment:

    # Final Challenge: Old MacDonald's Farm
  2. 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.

  3. Separate the input string into a list of strings containing animal:sound pairs.

  4. 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).

  5. 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

Submission of Lab 4

  • Use this link to submit your lab4.py file via Moodle.
  • This lab is due before the start of the next class.