Week 2
Solutions to Python Basics - Conditional Logic and Input
Exercise 1 - Login System
Here we create a simple username-password checker by comparing user input to stored variables, using nested if-statements.
# Store the name and password in 2 separate variables
name = "Alex"
password = "1234"
# First get the user to enter their name
input_name = input("Enter your username: ")
# Check against the name we have stored in 'name'
if input_name != name:
# The input_name does not equal the name
print("You have entered an incorrect username")
else:
# The input_name matches the name -> ask for password
input_password = input("Enter your password")
if input_password == password:
# Password is correct -> print a secret message
print("this is a secret")
else:
# Password didn't match -> print an error
print("You have entered an incorrect password")Extension Exercise 1 - Case Sensitivity
Here we use the .lower() function to ensure that our system isn't sensitive to capitalization in usernames - this also means that we need to store lowercase usernames in our "database".
Note that the **.lower() function does not reassign** the value of a variable automatically, so we have to reassign manually.
Extension Exercise 2 - Two users
The aim of this extension and the next is to become comfortable with many different levels of nested statements, and more complicated logical expressions.
Note: These examples are fairly ugly and contrived - in future weeks we will see how we could make this system far more efficient, and our code far more elegant.
Extension 3 - Bad Passwords
This is a fairly grueling exercise, but quickly recognizing the logical exclusivity which is implied by the indentation level of a piece of code is an essential skill for python programmers - so try and make sure you fully understand why this solution works!
Last updated
Was this helpful?