In Python (programming language), conditional statements allow your program to make decisions and execute certain code only if a condition is True. They are essential for controlling the flow of a program.
πΉ 1οΈβ£ The if Statement
The if statement executes a block of code only if the condition is True.
Syntax:
if condition:
# code to execute
Example:
age = 18if age >= 18:
print("You are an adult")
Output:
You are an adult
πΉ 2οΈβ£ The else Statement
The else statement executes a block of code if the if condition is False.
Syntax:
if condition:
# code if True
else:
# code if False
Example:
age = 15if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Output:
You are a minor
πΉ 3οΈβ£ The elif Statement
The elif (short for else if) statement allows you to check multiple conditions. It is used between if and else.
Syntax:
if condition1:
# code if condition1 True
elif condition2:
# code if condition2 True
else:
# code if all False
Example:
marks = 85if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: B
πΉ 4οΈβ£ Nested Conditional Statements
You can also nest if statements inside another if or else.
Example:
age = 20
gender = "male"if age >= 18:
if gender == "male":
print("Adult Male")
else:
print("Adult Female")
else:
print("Minor")
Output:
Adult Male
β Key Points
ifβ executes code when condition is Trueelifβ checks additional conditions if previousiforelifis Falseelseβ executes when all previous conditions are False- Conditions often use comparison operators (
>,<,==, etc.) and logical operators (and,or,not) - Indentation is critical; Python uses indentation to define code blocks