Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I improve on the current Python code?

I am just starting out with Python and decided to try this little project from Python Wiki:

Write a 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 You have been denied access. and terminate the program. If the password is correct, print You have successfully logged in. and terminate the program.

Here's my code. It works but it just doesn't feel right with these loop breaks and nested if statements.

# Password Guessing Program
# Python 2.7

count = 0

while count < 3:
    password = raw_input('Please enter a password: ')
    if password != 'SecretPassword':
        count = count + 1;
        print 'You have entered invalid password %i times.' % (count)
        if count == 3:
            print 'Access Denied'
            break
    else:
        print 'Access Granted'
        break
like image 714
Sahat Yalkabov Avatar asked Sep 05 '26 05:09

Sahat Yalkabov


1 Answers

You can replace your while loop with the following function:

def login():
    for i in range(3):
        password = raw_input('Please enter a password: ')
        if password != 'SecretPassword':
            print 'You have entered invalid password {0} times.'.format(i + 1)
        else:
            print 'Access Granted'
            return True
    print 'Access Denied'
    return False

You may also want to consider using the getpass module.

like image 62
Mark Byers Avatar answered Sep 06 '26 20:09

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!