prev next 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Using "for" to Repeat

You can repeat something with the "for" command.

If you say "for something in something:" with a colon (:) at the end, python will look for any indented lines afterwards and repeat them. Try this:


>>> for letter in secret:
...   print letter
...
c
r
o
c
o
d
i
l
e
>>>  

Think about your program - it is saying "for every letter in the secret, do this next thing." The computer repeats "print letter" nine times, once for each letter.

If it didn't work for you, don't worry. Press return and try again. Check that you put in the extra spaces and the punctuation. Spaces at the beginning of a line do make a difference in python.

Of course, in our game we shouldn't give away our secret word right away. So once you have the hang of it, try this:


>>> for letter in secret:
...   print '_',
_ _ _ _ _ _ _ _ _ 
>>>  

The comma at the end of print tells it not to start a new line.