Welcome!
Join our coding community
Ā© 2024 Ace Coding Academy
Code Examples
Example 1
Python checks each condition in order. Since 85 is not >= 90, it skips the first block. Since 85 >= 80 is True, it executes "Grade: B" and stops checking the remaining conditions. Only one block will ever execute.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Example 2
Since 15 is not > 30 or > 20, but 15 > 10 is True, Python executes the third block and prints the light jacket message. The order matters - Python stops at the first True condition.
temperature = 15
if temperature > 30:
print("It's very hot! Stay hydrated.")
elif temperature > 20:
print("Nice weather for a walk!")
elif temperature > 10:
print("A bit cool, wear a light jacket.")
else:
print("It's cold! Bundle up!")
Example 3
Python checks each color in sequence. When it finds that light_color == "yellow" is True, it prints "Caution! Prepare to stop." and skips the remaining conditions. The else catches any invalid colors.
light_color = "yellow"
if light_color == "red":
print("Stop!")
elif light_color == "yellow":
print("Caution! Prepare to stop.")
elif light_color == "green":
print("Go!")
else:
print("Invalid traffic light color.")
Example 4
This creates a simple menu system. Depending on what the user types, different messages appear. If they type anything other than "1", "2", or "3", the else block handles the error.
choice = input("Choose an option (1, 2, or 3): ")
if choice == "1":
print("You selected Option 1: New Game")
elif choice == "2":
print("You selected Option 2: Load Game")
elif choice == "3":
print("You selected Option 3: Settings")
else:
print("Invalid choice. Please select 1, 2, or 3.")