12: Iteration in Python

Try it:

Make code repeat as many times as you want
Iteration in Python: Make code repeat as many times as you want

Below you’ll see some example python code that contains a shopping list

Press Ctrl + Enter  to run the code.

This code creates a list called farm and adds three strings to that list: "cat", "dog" and "mouse"

Line 4 iterates through each string in the list using the variable animal to keep track of which animal the current iteration is working with. For example, animal stores "cat" the first time line 5 runs but then animal stores "dog" on the next iteration of line 5 and "mouse" on the final iteration of line 5.

Challenges:

Start by running the code.

  1. Change the cat to a pig

    When the code first runs you should see:

    Old McDonald had a farm E-I-E-I-O
    And on that farm he had a cat E-I-E-I-O
    Old McDonald had a farm E-I-E-I-O
    And on that farm he had a dog E-I-E-I-O
    Old McDonald had a farm E-I-E-I-O
    And on that farm he had a mouse E-I-E-I-O

    Change line 2 so that you see this when the code runs instead:

    Old McDonald had a farm E-I-E-I-O
    And on that farm he had a pig E-I-E-I-O
    Old McDonald had a farm E-I-E-I-O
    And on that farm he had a dog E-I-E-I-O
    Old McDonald had a farm E-I-E-I-O
    And on that farm he had a mouse E-I-E-I-O
  2. Add a zebra to the farm

    Add a new string inside the list on line 2 

  3. Repeat the whole song 5 times

    It might be helpful to look back at the theory page for this. You’ll need to choose which lines of code you want to repeat 5 times then indent them all (select and press tab) then write for i in range(5): above them.

On the next page you’ll get some code with both syntax and logic errors

Leave a Reply

Your email address will not be published. Required fields are marked *