[Tutor] Newbie Question

Andrei Kulakov ak@silmarill.org
Wed, 24 Jul 2002 05:30:11 -0400


On Tue, Jul 23, 2002 at 08:18:19PM -0400, Billie wrote:
> I am learning Python with the tutorial for non-programmers.
> 
> We are asked to write a program to keep track of how many times the user has entered the password wrong.  If more than 3 times, print "That must have been complicated"
> 
> How do you count a string statement?  Everything I've tried asks for integers.  I feel really stupid because I can't work this out.
> 
> password = "foobar"
> 

There are several ways.. you can add to the counter:

tries = 0

while 1:
    [ask for pwd]
    if good:
	dosomething
	break
    tries += 1
    if tries == 3:
	print "3 tries!"

You can subtract from tries:

tries = 3

while tries:
    [ask for pwd]
    if good:
	dosomething
	sys.exit()
    tries -= 1
print "3 tries!"

You can loop 3 times:

for i in range(3):
    [ask for pwd]
    if good:
	do something
	sys.exit()
print "3 tries!"
    
The first way shown here is probably better because you don't have to
exit the program.. using other ways, if you need to keep running, you
may set a flag for "got right pwd" and then after loop is done, print
"3 tries" only if the flag is not set.. But that's a bit of a
contraption I guess.

 - Andrei

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org