if…else Statement:
- It is used for decision-making in code.
- It allows executing a block of code if a certain condition is true, otherwise, another block of code if the condition is false.
Here’s the basic syntax:
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
Example:
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output: You are an adult.
elif (else if):
- We can also add more conditions using elif (short for “else if”)
age = 15
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Output: You are a teenager.
Nested if Statements:
- Nesting is using if statements inside other if statements.
- This allows you to check multiple conditions in a hierarchical manner.
age = 20
has_permission = True
if age >= 18:
if has_permission:
print("You can enter the event.")
else:
print("You need permission to enter the event.")
else:
print("You are not old enough to enter the event.")
Output: You can enter the event.