Working with Operators and If-Else Statements
Let's explore some common operators in Python using an apple-themed example.
# Equal to (==)
print("Is the apple red?", "red" == "red") # True
# Not equal (!=)
print("Is the apple not green?", "red" != "green") # True
# Greater than (>)
print("Is apple price greater than budget?", 60 > 50) # True
# Less than (<)
print("Is apple price less than budget?", 40 < 50) # True
# Greater than or equal (>=)
print("Do you have enough money?", 50 >= 50) # True
# Less than or equal (<=)
print("Is apple weight small?", 150 <= 200) # True
Learn how computers make decisions using if, elif, and else statements.
apple_color = "red"
if apple_color == "red":
print("This is a red apple! ")
else:
print("This apple isn't red.")
Explanation: If the apple is red, the program prints "red apple". Otherwise, it prints "not red".
is_healthy = True
if is_healthy:
print("This apple is good for you! ")
else:
print("Maybe choose a different fruit. ")
Explanation: If the apple is healthy, it prints "good". Otherwise, it suggests choosing another fruit.
apple_type = input("What color is the apple? ").lower()
if apple_type == "red":
print("Classic red apple")
elif apple_type == "green":
print("Tangy green apple")
elif apple_type == "yellow":
print("Sweet golden apple")
else:
print("Unknown apple variety")
Explanation: The program asks for the apple's color and provides a classification based on the input.
budget = int(input("What is your budget? "))
apple_price = int(input("What is the apple price? "))
if budget >= apple_price:
print("You can buy the apple! ")
else:
print("You don’t have enough money. ")
Explanation: The program compares the budget and apple price to determine if the apple can be bought.
color = input("Apple color (green / red): ")
if color.lower() == "green":
print("Not ready yet, wait! ")
elif color.lower() == "red":
print("Ripe and ready to eat! ")
else:
print("I don’t know this color. ")
Explanation: The program checks the color of the apple and tells you if it's ripe or not.