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

Dipo Elegbede delegbede at dudupay.com
Tue May 18 19:15:37 CEST 2010


thanks Steve, this response came handy.
I would have to take this home and read. if i encounter difficulties,
I'd get back to the house.
I'm grateful.
If I get more explanations though, it would be great.
Regards,

On 5/18/10, Steve Willoughby <steve at alchemy.com> wrote:
> 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".'
>
>
>


-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise
Application Development


More information about the Tutor mailing list