What are Conditional Statements?
Conditional statements in Python help your code make decisions! Think of them as traffic lights that tell your program where to go based on certain conditions.
Python provides three main conditional statements:
Statement | Meaning |
---|---|
if |
Executes a block of code only if the condition is True |
elif |
(short for "else if") Checks another condition if the first if was False |
else |
Executes a block of code if none of the previous conditions were True |
The if
Statement
Executes code only if the condition is True
.
age = 18
if age >= 18:
print("You are an adult!")
Real-life Example:
- If it’s raining, take an umbrella!
raining = True
if raining:
print("Take an umbrella!")
The if-else
Statement
Use else
to run a different block of code when the if
condition is False
.
age = 16
if age >= 18:
print("You can vote!")
else:
print("Sorry, you are too young to vote.")
Real-life Example:
- If you have money, buy candy , otherwise, cry.
has_money = False
if has_money:
print("Yay! Candy time! ")
else:
print("No candy today... ")
The if-elif-else
Statement
Use elif
to check multiple conditions.
score = 85
if score >= 90:
print("You got an A! ")
elif score >= 80:
print("You got a B! ")
elif score >= 70:
print("You got a C! ")
else:
print("You failed... ")
Real-life Example:
- If you are hungry, eat .
- Else if you are tired, sleep .
- Otherwise, watch Netflix .
hungry = False
tired = True
if hungry:
print("Time to eat! ")
elif tired:
print("Time to sleep! ")
else:
print("Let's watch Netflix!")
Nesting if
Statements
You can put if
statements inside another if
statement.
age = 20
gender = "male"
if age >= 18:
if gender == "male":
print("You are an adult male!")
else:
print("You are an adult female!")
else:
print("You are still a minor!")
Real-life Example:
- If the store is open, check if they sell ice cream.
store_open = True
sells_ice_cream = False
if store_open:
if sells_ice_cream:
print("Buy ice cream!")
else:
print("No ice cream here...")
else:
print("The store is closed.")
Summary
Statement | Purpose |
---|---|
if |
Checks a condition and executes code if True |
else |
Executes code if the if condition is False |
elif |
Checks another condition if the first if was False |
Nested if |
Allows checking multiple conditions inside another if |
Now you're a Python decision-making master!
Try using conditional statements in your own code and make your programs smarter!
0 Comments