and, or, not

Consider again our password code:

real_password = "friend"
user_password = input("What's the secret password? ")
tries = 1
while user_password != real_password:
    print("Wrong!")
    user_password = input("What's the secret password? ")
    tries = tries + 1

print("That is correct. It took you", tries, "tries.")

How can we make this code give the user only three tries to guess the password? Using things you already know, you could do it like this:

real_password = "friend"
user_password = input("What's the secret password? ")
tries = 1
keep_going = user_password != real_password
while keep_going:
    print("Wrong!")
    user_password = input("What's the secret password? ")
    tries = tries + 1

    if user_password == real_password:
    	keep_going = False

    if tries == 3:
    	keep_going = False

if user_password == real_password:
    print("That is correct.")
else:
    print("Wrong! The password was", real_password)

Run the above code in Thonny. Study it until you understand how it works.

Here’s a better way to do the same thing:

real_password = "friend"
user_password = input("What's the secret password? ")
tries = 1
while user_password != real_password and tries < 3:
    print("Wrong!")
    user_password = input("What's the secret password? ")
    tries = tries + 1

if user_password == real_password:
    print("That is correct.")
else:
    print("Wrong! The password was", real_password)

and is a boolean operator. It allows us to combine two boolean expressions into a single boolean expression. If both of the expressions are True, then and will make the whole expression True. Here’s an example of how the computer evaluates and expressions:

    real_password = "friend"
    user_password = "cheese"
    tries = 3
    keep_going = user_password != real_password and tries < 3
 -> keep_going = "cheese" != "friend and 3 < 3
 -> keep_going = True and False
 -> keep_going = False

previous: exercises next: exercises