[Tutor] Loop basics (was Re: what is wrong with this syntax?)

Steve Willoughby steve at alchemy.com
Tue May 18 19:02:45 CEST 2010


I'm changing the subject line because this is going into a different topic.

On Tue, May 18, 2010 at 05:39:50PM +0100, Dipo Elegbede wrote:
> A LITTLE EXPLANATIONS ON CONTINUE WOULD BE APPRECIATED TOO.
> in a recap, i would appreciate any brief explanation on
> 1. break
> 2. continue
> 3. while loop

These are the basic constructs in many languages for repeating a set of
tasks over and over, as long as some condition remains true.  Say you had
a function which asks the user a yes or no question and returns True if
they said 'yes' or False if they said 'no'.  

You want to play a game as long as they keep saying they're willing to
play, so assuming a function play_game() which does the actual playing,
making Python keep doing this repeatedly would look like this:

while ask_yes_or_no('Do you want to play a game?'):
  play_game()

If you get into the loop and decide you want to bail out early rather
than waiting for the condition to become False on its own, you can
just put a break statement inside the loop.  As soon as Python encounters
that break, it will stop the loop.

while ask_yes_or_no('Do you want to play a game?'):
  print 'Okay, that will be fun.'
  if not ask_yes_or_no('Are you sure, though?'):
    break
  play_game()


continue is like break in that it upsets the normal flow of the loop
body, but whereas break stops the loop completely, continue abandons
only THIS run through the loop, jumps immediately back to the top,
and continues from there, testing the condition to see if another trip
through the loop is allowed at this point.

For example, you might write the ask_yes_or_no function like this:

def ask_yes_or_no(prompt):
  while True:
    answer = raw_input(prompt)
    if answer == 'both':
      print 'Now that's just silly, try again.'
      continue
    if answer == 'yes':
      return True
    if answer == 'no':
      return False
    print 'Please answer "yes" or "no".'




More information about the Tutor mailing list