[Tutor] Looping

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 15 Apr 2002 11:55:12 +0200


On  0, "Crane, Adam" <ACrane@computer2000.co.uk> wrote:
> Ok, I'm a newbie to Python, so please forgive me if this sounds stupid :)
> But I'm not really sure where to send this...
> 
> Is there a way to stop text from looping using while?  For example, if I
> used this in a program, the indented text would loop:
> 
> password = raw_input("Password:")
> while password != "password":
>                print "Wrong Password"
> 
> I still having a lot of reading to do on Python, but this is really bugging
> me.  This is probably really obvious, but any help would be appreciated.

Well, the while keeps doing whatever is inside its block, as long as
password isn't equal to "password". That's what while does. Maybe you were
looking for 'if'?

Since you don't change password inside the loop, it loops forever.

A solution is to ask for the password inside the loop again:

password = raw_input("Password:")
while password != "password":
   print "Wrong Password"
   password = raw_input("Password:")
   
This has the disadvantage that the same line is on two places, and if you
ever change one, you might forget about the other. A common way to spell
this in Python is like "do this forever: ask for the password, and if its
right, then stop." Which you write like this:

while 1:
   password = raw_input("Password:")
   if password == "password":
      break

This keeps repeating while '1' is true (it always is), but the 'break'
allows it to exit the loop.
-- 
Remco Gerlich