When to use what type of repetition in a program #TC1014

A for loop repeats the execution of a block of statements a fixed number of times. A list of values, or a string, is used to determine the number of times the block of code will be repeated. The block of code is executed once for each item in the list, or each character in the string.

Programmers have a number of jargon words that refer to loops; repetition is also called iteration and the for loop is sometimes called a definite loop because we can work how many repetitions there will be from the program (the while loop, which we will deal with later, is ‘indefinite’, i.e. we don’t know how many times it will iterate until the program is run).

Open the following program loopThroughName.py in IDLE and run it.

# loopThroughName.py
# this program loops through a users first name
# displaying each letter of their name on a separate line
# D.H. January 5th 2005

firstName = raw_input("Please enter your first name: ")
print
print "Each letter of your name follows "
print

for letter in firstName:
     print letter

Deja un comentario