[Tutor] Looping

Crane, Adam ACrane@computer2000.co.uk
Mon, 15 Apr 2002 11:04:47 +0100


Thank you!  As I thought, it was obvious, but I just couldn't figure that
one out.  I think it must've been the lack of coffee :)

Thanks again,
Adam

-----Original Message-----
From: Remco Gerlich [mailto:scarblac@pino.selwerd.nl]
Sent: 15 April 2002 10:55
To: tutor@python.org
Subject: Re: [Tutor] Looping


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


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.