Using len()

Jonathan Gardner jgardner at jonathangardner.net
Sat Mar 11 10:39:40 CET 2006


Methinks you are confused about the structure of your program.

If we write the program out in plain English in the form of a recipe,
it should look something like this:

1. Get input.
2. Check to see if they guessed right.
3. If not, go back to 1.

This structure hints at an infinite loop. The breakout condition is a
correct guess. You always need a breakout condition, or the loop goes
on forever. (Sometimes you do want an infinite loop. Think about how
you would write a web server.)

(Note on variable names: "your" and "my" are not clear. Usually, first
person ("I", "me", "my") refers to the programmer. The second person
("you", "your") is rarely used. "You" could be the user, the computer,
or another programmer. Just use third person ("it", "he", "they").

So, we write an infinite loop in Python:

while True:

  # Get input
  guess = raw_input()

  # Is the guess right?
  if guess == num:
    # Yep. Break out of the loop.
    break

  # Otherwise, loop again.

You could put the breaking condition in the "while" line. But since it
appears in the middle of the loop, this is difficult to do. So just put
it in explicitly in the middle and call it a day.




More information about the Python-list mailing list