The if-else
statement allows you to execute one block of code if a condition is true, and another block of code if the condition is false.
if condition:
# code if condition is True
else:
# code if condition is False
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
Python checks the condition. If it is true, the code inside the if
block runs. Otherwise, the code inside the else
block runs.
# Example 1
num = -5
if num > 0:
print("Positive number")
else:
print("Zero or negative number")
# Example 2
temperature = 20
if temperature > 30:
print("It's a hot day")
else:
print("It's a cool day")
# Example 3
name = "Bob"
if name == "Alice":
print("Hello, Alice!")
else:
print("You are not Alice")
# Example 4
score = 40
if score >= 50:
print("You passed!")
else:
print("You failed!")
# Example 5
is_raining = True
if not is_raining:
print("Let's go for a walk!")
else:
print("Better to stay inside")