AND Operator
Use and when every condition must be true:
print("To enter you need the secret word and the secret number!")
word = input("What is the secret word? ")
number = int(input("What is the secret number? "))
if word == "solitude" and number == 2011:
print("Correct! You may enter!")
else:
print("Incorrect! Get out of here!")
The body of the if runs only when word == "solitude" and number == 2011 are both true.
Logical Operators Task 1 – Three Easy Questions
Print a special message only if all answers are correct (combined with and):
capital = input("What is the capital of Germany? ")
formula = input("What is the chemical formula for water? ")
year = input("What year did World War Two end? ")
if capital == "Berlin" and formula == "H2O" and year == "1945":
print("You absolute genius!")
else:
print("Bit awkward, I thought you'd do better...")
OR Operator
Use or when any one of the conditions being true is enough:
letter = input("Enter a letter: ")
if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u":
print("You entered a vowel.")
else:
print("You entered a consonant.")
Tip: comparisons must be repeated with or. (Later you can use membership: if letter in "aeiou":)
Logical Operators Task 2 – Twins?
Check if someone matches your favourite colour and/or age using and/or:
fav_colour = input("What's your favourite colour? ")
age = int(input("What's your age? "))
my_colour = "green"
my_age = 15
if fav_colour == my_colour and age == my_age:
print("Snap! Are you my twin?")
elif fav_colour == my_colour or age == my_age:
print("Spooky! You're a bit like me.")
else:
print("We're not so similar, you and I.")