[Tutor] New 2 Python- Script 'kill' function/Ubuntu File Browser hide hidden files

bob gailer bgailer at alum.rpi.edu
Sun Jan 13 21:58:16 CET 2008


Ian Egland wrote:
> Hello, I am new to Python (and OO programming in general) and I have a 
> script that I made through a tutorial.
>
> # -*- coding: utf-8 -*-
> # Copyright (C) 2007-2008 Ian Egland
> # From the Non-Programmer's Guide to Python By Josh Cogliati
> # 5.3 Exercise 1
> # Modify the password guessing program to keep track of how many times 
> the user has entered the password wrong.
> # If it is more than 3 times, print "That must have been complicated."
>
>
> tries = 3
> password = "What is the password?"
> while password != "thepassword":
>     print "You have", tries, "remaining."
>     print "What is the password?"
>     password = raw_input("> ")
>     if password == "thepassword":
>         print "You got the password in only", 3 - tries, "tries!"
>     else:
>         tries = tries - 1
>         if tries == 0:
>             print "Sorry... but that was wrong. (again) Your not as 
> smart as I thought..."
>         else:
>             print "I am sorry, that was incorrect. Please try again."
>             quit
>
> Now I cant see anything wrong with it... except that I don't think 
> that quit is the right function as when I run it this happens.
quit is a function. The line above is a reference to the function rather 
than a call to the function. To call a function you must always add () 
e.g. quit().

Your goal here is to break out of the while loop. You can accomplish 
that with the break statement in place of the quit function call.

I'd code this differently, to take advantage of the for loop and to 
reduce redundant code. I also corrected spelling, introduced a 
"constant" and enhanced things so try is singular or plural as needed.

MAXTRY = 3
for tries in range(MAXTRY, 0, -1):
    if tries == 1:
        print "You have 1 try remaining."
    else:
        print "You have", tries, "tries remaining."
    print "What is the password?"
    password = raw_input("> ")
    if password == "thepassword":
        attempts = MAXTRY - tries + 1
        if attempts == 1:
            print "You got the password in only 1 try!"
        else:
            print "You got the password in only", attempts, "tries!"
        break
    elif tries > 1:
        print "I am sorry, that was incorrect. Please try again."
    else:
        print "Sorry... but that was wrong. (again) You're not as smart 
as I thought..."

That is more than you requested, and I hope it all helps your learning.

[snip]


More information about the Tutor mailing list