If, Else, Elif

Conditional statements allow your program to make decisions. In Python, we use if, else, and elif to execute different blocks of code based on conditions.

These statements help control the flow of a program.

1. IF STATEMENT

The if statement checks a condition.
If the condition is True, the code inside the block runs.

Syntax:

if condition:
# code to execute

Example:

age = 18if age >= 18:
print("You are eligible to vote.")

If the condition is true, the message will be printed.

2. ELSE STATEMENT

The else statement runs when the condition in the if statement is False.

Syntax:

if condition:
# code if true
else:
# code if false

Example:

age = 16if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Since the condition is false, the else block runs.

3. ELIF STATEMENT

The elif (else if) statement checks multiple conditions.
It is used when you have more than two possible outcomes.

Syntax:

if condition1:
# code
elif condition2:
# code
else:
# code

Example:

marks = 75if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
else:
print("Fail")

The program checks conditions one by one.
When a true condition is found, it executes that block and stops checking further conditions.

IMPORTANT RULES

• Indentation is very important in Python.
• Use colon (:) after if, elif, and else.
• Only one else block is allowed.
• You can use multiple elif blocks.

NESTED IF STATEMENT

You can place an if statement inside another if statement.

Example:

age = 20
has_id = Trueif age >= 18:
if has_id:
print("You can enter.")
else:
print("You need an ID.")
else:
print("You are underage.")

WHY CONDITIONAL STATEMENTS ARE IMPORTANT

• They help programs make decisions
• They control program flow
• They allow logical problem solving

Understanding if, else, and elif is essential for building real-world Python applications.

Home » PYTHON FUNDAMENTALS (PYF) > Control Flow > If, Else, Elif