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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With