Security and Privacy in a Networked World/Programming in Python

Allikas: KakuWiki
Mine navigeerimisribaleMine otsikasti

Iteration

Typically, there are three kinds of iteration used in programming languages:

  • counted iteration (for)
  • pre-test iteration (while)
  • post-test iteration (do while)

However, Python only uses the two former ones, there is currently no post-test iteration in Python (although it is possible by combining other statements).

The counted iteration, called "for" in most languages, uses a special variable (counter) to count the steps (thus the "for" means "for every value of the counter (do something)"). The version used in Python is a little different from many other languages (in some of them, a "for each" does similar things to "for" in Python). In Python, the iteration is used to move through a range of numbers or elements of a set. For example, we can count numbers from 1 to 12 (e.g. for months in a year):

for x in xrange(1,13):
  print x

Note: The range limit must be larger by one!

We can also use the same statement to print a sentence letter by letter:

sentence = "I like Python!"
for x in sentence:
  print x

The pre-test and post-test iteration are rather similar, but the latter is always carried out at least once, while the former can also be totally ignored. They do not use a special control variable, rather they check the value of a variable already in use. In Python, "while" is used for the pre-test iteration:

counter = 1
while (counter < 5):
  print "The counter is now at ", counter
  counter = counter - 1


In this example, the while-block will check whether the value of the counter is less than 5 (it is, as it is initially set to 1) and then proceed until the condition is not met anymore (the counter reaches 5).

Note: the last line of the example is a classic confuser for beginners - they tend to interpret it as comparison ("How can something equal itself plus something?"), but it is actually assigning a "larger by one" value to the variable, or adding one to it.

If we set the counter to the initial value of 8, the program will not display anything at all - the initial check fails (the counter is already larger than 5) and the whole while-block is ignored.

There are also two commands which are often found in combination with the while-block:

  • break - stops the iteration and moves to the next statement after the while-block.
  • continue - ends the current round, moving to the main condition for the next round's check.

An example: Text entry with the length check (must be at least 5 characters):

while True:
  text = raw_input("Enter text (at least 5 symbols): ")
  if text == 'stop':
    break
  if len(text) < 5:
    continue
  print 'The text length was OK'

Note: this example uses a technique called "eternal loop". In this case, the main while-block keeps repeating until the ending condition ("stop" is entered) is met.