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.

# Boolean values
x = True
y = False
print(x, y)
# Simple if with boolean
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
# Comparisons give booleans
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

fruits = ["apple", "cherry", "banana"]
favorite = "chocolate"
found = favorite in fruits
print(found)

Boolean Operators used to combine the multiple values of multiple boolean values.

age = 6
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(10 > 5)
print(2 == 3)

💡 Predict the output.

Check Age

age = 15
if age >= 18:
  print("Adult")
else:
  print("Child")

💡 What will it print?

Guess favorite food

favorite = ["Pizza", "Nasi Goreng", "Kebap", "Soto Ayam"]
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?

number = 8
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"

score = input("Input your score")
if(score > 60):
 print("Pass")

else print "Fail".

Using and

temp = 25
if temp > 20 and temp < 30:
  print("Nice weather!")
else:
  print("Not nice.")

💡 Predict the output.

Using or

day = "Sunday"
if day == "Saturday" or day == "Sunday":
  print("Weekend!")
else:
  print("Weekday.")

💡 Try changing the value of day.

Using not

is_raining = False
if not is_raining:
  print("Go outside!")
else:
  print("Take an umbrella.")

💡 Predict the output.

If…Elif…Else

score = 85
if score >= 90:
  print("Excellent")
elif score >= 60:
  print("Good")
else:
  print("Try harder")

💡 What will it print?

Mystery Output

x = 5
y = 10
if x * 2 == y:
  print("Equal!")
else:
  print("Not equal!")

❓ Predict the output without running first.