fbpx

Repeating with Loops and Lists

Lists of numbers

Until now, we’ve had to write out numbers every time we want Tina to move. We can use a list of numbers and a loop to get her to move many times!

Assignment:

The code number_list = [1,2,3,4,5,6,7,8,9,10] is where Tina gets her numbers from. Can you change the numbers in the list to change how she moves? Make sure that your list starts and ends with square brackets ([]), and has a comma (,) in between every number.

Loops of lists

So far we’ve been telling Tina to do things over and over. Remember the example we used in Color section in previous topic?

There’s a lot of repetition. If we give Tina a list of colors and tell her to do the same thing with each color, we can make the same picture with much less code!

Assignment:

We can now easily change how many times Tina draws as well. Try adding a new color name to the list. Here’s what it would look like to add "yellow" to the list:

color_list = ["black", "blue", "purple", "green", "yellow"]

Don’t forget the quotes ("") around your color word!

Hit a snag? Don’t worry! Tips:

  • Remember to put your color name in quotes ("")
  • Remember to include a comma (,) in between each color name and the next one
  • Remember to begin and end your list with square brackets ([ and ])

Changing Colors

We can loop over a list of colors and tell Tina to turn that color. Run this program, and see where the colors come from. What happens if you add or remove colors from the list?

Assignment:

Want to make this program your own? Change what tina does inside the for loop. What else could she do for each color?