[Tutor] Inexperienced fool

Andrei Kulakov ak@silmarill.org
Wed, 7 Aug 2002 16:45:06 -0400


On Tue, Aug 06, 2002 at 11:57:20PM +0100, steven bruce wrote:
> Hi
> 
> I know nothing about programming except a bit of HTML.  I am trying to do a 
> couple of hours each night trying to learn Python.  I am doing the modules 
> in the beginners section and cant for the life of me get a password 
> guessing programme to keep track of how many times the wrong password has 
> been entered.
> help would be greatly appreciated.
> very embarrassed
> 
> Steve
>
Here's an example:

Enter password: sec
You've entered wrong password 1 times.
Enter password: doh
You've entered wrong password 2 times.
Enter password: argh
You've entered wrong password 3 times.
Enter password: secret34
Right you are!

Here's code:

pw = "secret34"
count = 0

while 1:
    answer = raw_input("Enter password: ")
    if answer == pw:
        print "Right you are!"
        break
    else:
        count = count + 1
        print "You've entered wrong password %d times." % count

Here's explanation:

while 1: loops until you break out of it. It's usually used like this:

while 1:
    [do stuff, sometimes set flag]
    if flag is set: break

flag is simply a variable that is first set to 0 and then set to 1 if
some condition is met. Or as in our case here we can compare a password
to user's answer.

2nd line gets user's answer into variable called "answer". 3rd line
compares that answer to variable 'pw' which holds password. If they're
the same, we print "right you are" and break out of the loop; since the
whole program is in the loop, it exits right after that.

else runs if password is not equal to what user entered; here we add
one to variable called count (which starts at 0); and then we print out
the value of count.

Please save this code in a file and play around with it, changing it to
stop after 3 tries, etc. If you have further questions, start with this
code, and ask why your changes don't work or don't do what you expect,
so that we don't have to start all over again. I've already gave you
some code before, IIRC, and I don't know what black hole it disappeared
into ;-).

> 
> 
> 
> 
> _________________________________________________________________
> MSN Photos is the easiest way to share and print your photos: 
> http://photos.msn.com/support/worldwide.aspx
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player: python, linux, console.
get it at: http://silmarill.org/cymbaline.htm