Week 4
Solutions to While, For and Challenges
Exercise 1 - Finishing Login System
# 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:")
remaining_attempts = 3
# if the password is wrong and we have attempts left, ask again
while (input_password != users[input_name]) and (remaining_attempts > 0):
# re-enter the captcha
captcha_answer = input("Wrong password! What is 7 + 36? ")
captcha_answer = int(captcha_answer) # convert to integer
# captcha was wrong, so stop them trying
if captcha_answer != 43:
print("You are not human!")
break
input_password = input("Try again:")
remaining_attempts = remaining_attempts - 1
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 run out of password attempts!")
else:
# input_name is not in the users dictionary
print("Unknown username")Exercise 2.1 - Hip to be Square
Exercise 2.1 Extension - Hollow Square
Exercise 2.2 - Hidden message via For Loop
Exercise 2.3 - Pythagorean Triples
Extension 1 - Goat Latin
Extension Extra 1 - Advanced Goat Latin
Last updated