def login(user, password):
'''Return True iff the login is successful using credentials (user,
password).
Return False if the login is not successful, either because of wrong
credentials or because the user was locked out. Print a message if
a locking out occurs.
Locking out occurs if three attempts in a row are made to log in with
invalid credentials.
The credentials are stored in the global variables usernames and passwords,
with credential pairs being users[i], passwords[i].
Modify the global n_attempts to keep track of attempts to login with
invalid credentials that occur one after each other.
Arguments:
user -- a string
password -- a string
'''
global unsuccessful_attempts
#can use users passwords
if unsuccessful_attempts >= 3:
return False
if user not in users:
unsuccessful_attempts += 1
if unsuccessful_attempts >= 3:
print("You're locked out now!")
return False
if passwords[users.index(user)] == password:
unsuccessful_attempts = 0
return True
else:
unsuccessful_attempts += 1
if unsuccessful_attempts >= 3:
print("You're locked out now!")
return False
def initialize():
'''Set the globals variables users and passwords, and
initialize the global unsuccessful_attempts to 0
'''
global users, passwords, unsuccessful_attempts
#usernames and passwords. users[i], passwords[i]
#are matching pairs
users = ["foster", "collins", "thywissen"]
passwords = ["praxis!", "elegance", "midterm"]
#The current number of consecutive unsuccessful attempts
unsuccessful_attempts = 0
initialize()
if __name__ == '__main__':
#Test case 1: a lock out should occur.
initialize()
login("foster", "praxis!")
login("guerzhoy", "a234fsadkjl")
login("guerzhoy", "a234fsadkjl")
login("guerzhoy", "a234fsadkjl")
if login("thywissen", "midterm") == False:
print("Test 1 passed")
else:
print("Test 1 failed")
#Test case 2: a lock out should not occur: 3 failed
#logins, but with one succesful login in between
initialize()
login("guerzhoy", "a234fsadkjl")
login("foster", "praxis!")
login("guerzhoy", "a234fsadkjl")
login("guerzhoy", "a234fsadkjl")
if login("thywissen", "midterm") == True:
print("Test 2 passed")
else:
print("Test 2 failed")
In order to look up the password for user user, we need to figure out the i such that users[i] == user. Then, we can use that information to look up passwords[i].
users.index(user) gives us that i. We then can use passwords[users.index(user)] in order to get the password associated with the user.
We set up a global variable called unsuccessful_attempts. The function login modifies it as appropriate (setting it to 0 when there is a successful attempt, increasing it when there is an unsuccesful attempt.) Basically, login() makes sure that unsuccessful_attempts always contains the current number of consecutive unsuccessful login attempts. That way, login() can return False when unsuccessful_attempts is 3.