[Tutor] while loops,password

alan.gauld@bt.com alan.gauld@bt.com
Wed, 14 Aug 2002 15:42:47 +0100


> > while password != "unicorn":
> >     print "You've guessed",a,"times."
> >     password = raw_input("Password?:")
> >     a=a+1
> > 
> >     if password=="unicorn":
> >         print "Welcome in, you took ", a, "attempts."
> > 
> >     #I added
> >     elif a>3:
> >         break
> > 
> > The *break* breaks out of the while loop.
> >
> 
> surely you want it to break if you got the answer right 
> aswell?? 

It will breakj naturally coz thats the terminating 
condition of the loop.

But really the whole if/else bit should be outside 
the loop. The loop is supposed to get the input and 
count the attempts. Once we've done that we can 
display the findings. As ever, separate display 
from processing. 

> so yeah, what do you think?? does that look better?? 

I don't think so, I prefer to use a boolean combined 
condition in the while. break within a while loop is 
an oftenseen Python idiom, but its easy to overdo it!
The loop condition itself should be the normal exit, 
break is for the occasional abnormal case..

IM(NS)HO :-)

Alan g