We can iterate a list using a for loop
#!/usr/bin/python items = [ "Abby","Brenda","Cindy","Diddy" ] for item in items: print(item)
The for loop can be used to repeat N times too:
#!/usr/bin/python for i in range(1,10): print(i)
If you are unsure how many times a code should be repeated, use a while loop.
correctNumber = 5 guess = 0 while guess != correctNumber: guess = input("Guess the number: ") if guess != correctNumber: print('False guess') print('You guessed the correct number')
We can combine for loops using nesting. If we want to iterate over an (x,y) field we could use:
#!/usr/bin/python for x in range(1,10): for y in range(1,10): print("(" + str(x) + "," + str(y) + ")")
Nesting is very useful, but it increases complexity the deeper you nest.