New to programming question

Joal Heagney joal at bigpond.net.au
Fri Apr 1 23:16:39 EST 2005


Joal Heagney wrote:
> Steve Holden wrote:
>> I suppose this would be far too easy to understand, then:
>>
>> pr =['Guess my name', 'Wrong, try again', 'Last chance']
>> for p in pr:
>>   name = raw_input(p+": ")
>>   if name == "Ben":
>>     print "You're right!"
>>     break
>> else:
>>   print "Loser: no more tries for you"
>>
>> regards
>>  Steve
> 
> 
> THIS is why I like python! There's always a simple, easy to understand 
> way to do something. If it looks complex, then there must me something 
> wrong.
> 
> Joal

And now that I've looked at the documentation of the for loop, I 
understand it as well! :)

The following explaination is for Ben, so he knows what's going on.
 From the documentation, with a little rewriting.


"The for statement is used to iterate over the elements of a sequence 
(such as a string, tuple or list) or other iterable object:

for target_list "in" expression_list:
	<do this first>
else:
	<now do this last>

The expression list is evaluated once and should yield a sequence(such 
as a string, tuple, list or iterator object).
Each item in the sequence is assigned to the target_list variable in 
turn. Then the "do this first" instructions are then executed once for 
each item in the sequence.
When the items are exhausted (which is immediately when the sequence is 
empty), the "now do this last" instructions in the else statement, if 
present, are executed, and the loop terminates.

A break statement executed in the first section terminates the WHOLE 
loop without executing the else clause. A continue statement executed in 
the first stage skips the rest of these instructions for that loop and 
continues with the next item, or with the else clause if there was no 
next item."

So copying Steve's example:

 >> pr =['Guess my name', 'Wrong, try again', 'Last chance']
 >> for p in pr:
 >>   name = raw_input(p+": ")
 >>   if name == "Ben":
 >>     print "You're right!"
 >>     break
 >> else:
 >>   print "Loser: no more tries for you"

This allows us to execute the else clause if the name is guessed 
incorrectly three times.
However, if the name is guessed correctly, then the break statement 
pulls us completely out of the loop without executing the else clause.

My original example attempted to do this by splitting the loop up into a 
series of different cases because I was unaware of this additional 
behaviour with the for loop expression. Steve's method = much better.

Joal



More information about the Python-list mailing list