[Tutor] Help with a while or a for loop that only allows three tries
Don Arnold
Don Arnold" <darnold02@sprynet.com
Sun Apr 13 13:16:01 2003
----- Original Message -----
From: "Danny" <wheelcrdan@hotmail.com>
To: <tutor@python.org>
Sent: Sunday, April 13, 2003 11:37 AM
Subject: [Tutor] Help with a while or a for loop that only allows three
tries
Hi Everyone
I'm working through the ActivePython Documents. One of the exercises is to
make a password program that exits after three tries. I'm confused I've
tried some different things having none of them be successful.
Also some times I see a while loop that starts out like
while 1:
what does that tiring to say, only go through the loop once. Or is that a I
if so what would you use something like that example for?
[-- my reply --]
A while loop executes its body as long as its condition is true. 1 will
always evaluate as true, so using it as the looping condition gives an
endless loop. With an endless loop, there should be a condition in the loop
body that causes the loop to terminate, usually by executing the break
statement. So, your password program could look something like this:
tries = 0
while 1:
password = raw_input('Enter your password: ')
if password == 'DANNY':
print 'password accepted'
break
else:
tries += 1
if tries == 3:
print 'invalid password'
break
Or, you could use the value of your loop counter in the while condition:
tries = 0
while tries < 3:
password = raw_input('Enter your password: ')
if password == 'DANNY':
print 'password accepted'
break
else:
tries += 1
else:
print 'invalid password'
The while/else construct may look a little strange, but it's pretty simple:
the else clause only executes if the loop terminated normally (in other
words, it wasn't exited with a break statement).
HTH,
Don