Week 3
Solutions to Lists, Dictionaries, Error Handling and List Slicing
Exercise 1 - Login System MKII
# Store the username and password as key-value pairs 'username : password'
users = {"alex" : "1234", "joe" : "5678", "luke" : "0000"}
# store the bad passwords in a list
bad_passwords = ["password", "pass", "word", "1234"]
# store custom welcome messages for each user in users
welcome_msgs = {"alex" : "Greetings Alex",
"joe" : "Howdy Joe",
"luke" : "Good day Luke"}
# Add a captcha by getting the user to answer a question
answer = input("What is 4 + 21? ") # always reads a string
answer = int(answer) # convert string input to integer
# if captcha answer was wrong, print error message and quit program
if answer != 25:
print("You are not human!")
exit() # stops the script from being run
# Now get user to enter their name
input_name = input("Enter your username: ")
input_name = input_name.lower() # Convert to lowercase
# check if the username exists in our users-password dictionary
if input_name in users.keys():
# input_name exists so check password matches
input_password = input("Enter your password:")
if input_password == users[input_name]:
# password is correct, print custom welcome message
print(welcome_msgs[input_name])
# check if the password is in the bad list
# use lower() to ignore case when checking for bad passwords
if input_password.lower() in bad_passwords:
# password is bad so give the option to change it
change_password = input("Warning: Password sucks, change?(y/n):")
if change_password == "y":
# user wants to change, so get a new one
new_password = input("Enter new password:")
users[input_name] = new_password # store for that user
print("Password changed to:" + new_password)
else:
# password invalid
print("You have entered an incorrect password")
else:
# input_name is not in the users dictionary
print("Unknown username")Extensions
Extension 1 - Incompetent User Warning
Extension 2 - List Slicing Fun
Extension 3 - Forced Palindromes
Extension 4 - Random Captcha
Last updated