Lesson 7 - Booleans
Python Logical Conditions and Booleans
Booleans are special values in Python that can only be
True or False. They are often used with logical conditions
to control how your program runs.
x = True
y = False
print(x, y)
is_hungry = True
if is_hungry:
print("Time to eat!")
Comparison Operators:
| Equal | a == b |
Not Equal | a != b |
| Greater than | a > b |
Less than | a < b |
| Greater than or equal | a >= b |
Less than or equal | a <= b |
print(5 > 3) # True
print(10 == 5) # False
print(10 != 5) # True
Membership Operators used to check if a value is a member of a list or not. Operators are in and not in
favorite = "chocolate"
found = favorite in fruits
print(found)
Boolean Operators used to combine the multiple values of multiple boolean values.
height = 52
is_allowed = (age >= 8 or height >= 48)
print(is_allowed)
not_allowed = not is_allowed
print(not_allowed)
and - true if both conditiona are true.or - true if one of conditions is true.not - flips the result.
Tip: Conditions let your program make decisions. Try changing the values and see how the program follows different paths.
True or False?
print(2 == 3)
💡 Predict the output.
Check Age
if age >= 18:
print("Adult")
else:
print("Child")
💡 What will it print?
Guess favorite food
guess = input("Guess my favorite food")
found = guess in favorite
if found:
print("Yes, thats my favorite food")
if not found:
print("No, I don't like that")
Make your own favorite food list
Even or Odd?
if number % 2 == 0:
print("Even")
else:
print("Odd")
💡 Try changing the number.
Pass or Fail
Ask the user for their exam score.
If it’s 60 or higher, print "Pass"
if(score > 60):
print("Pass")
else print "Fail".
Using and
if temp > 20 and temp < 30:
print("Nice weather!")
else:
print("Not nice.")
💡 Predict the output.
Using or
if day == "Saturday" or day == "Sunday":
print("Weekend!")
else:
print("Weekday.")
💡 Try changing the value of day.
Using not
if not is_raining:
print("Go outside!")
else:
print("Take an umbrella.")
💡 Predict the output.
If…Elif…Else
if score >= 90:
print("Excellent")
elif score >= 60:
print("Good")
else:
print("Try harder")
💡 What will it print?
Mystery Output
y = 10
if x * 2 == y:
print("Equal!")
else:
print("Not equal!")
❓ Predict the output without running first.