How to Use if, elif, and else Statements in Python
Conditional statements are fundamental in Python programming. They allow your code to make decisions and execute different blocks of code based on specific conditions. In this article, you'll learn how to use if, elif, and else statements in Python, with syntax, code examples, outputs, and clear explanations.
Table of Content
What are Conditional Statements?
- Definition: Conditional statements let your program choose which code to run based on whether a condition is
TrueorFalse. - Use Cases: Decision making, branching logic, input validation, and more.
- Benefits: Makes your code dynamic, interactive, and responsive to different situations.
01. The if Statement
The if statement executes a block of code only if a specified condition is True.
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
- If the condition
x > 5is true, the code inside theifblock runs. - If the condition is false, nothing happens.
02. The if-else Statement
The else statement provides an alternative block of code if the if condition is False.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output:
x is not greater than 5
- If the
ifcondition is not met, theelseblock runs. - Ensures that one of the two code blocks will always execute.
03. The if-elif-else Statement
The elif (short for "else if") allows you to check multiple conditions in sequence.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Output:
Grade: B
- Checks each condition in order from top to bottom.
- The first condition that is
Trueruns its block, and the rest are skipped. elseis optional and runs if none of the previous conditions are met.
04. Nested if Statements
You can place one if statement inside another to check multiple levels of conditions.
num = 15
if num > 0:
if num % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Non-positive number")
Output:
Positive odd number
- The outer
ifchecks if the number is positive. - The inner
ifchecks if it's even or odd. - Nested
ifstatements allow for more complex decision-making.
05. Comparing if, elif, and else in Python
| Statement | Purpose | Required? | How Many? | Notes |
|---|---|---|---|---|
if |
Checks a condition | Yes | One per block | Starts the conditional chain |
elif |
Checks more conditions | No | Zero or more | Comes after if |
else |
Default action | No | Zero or one | Comes last, no condition |
Conclusion
The if, elif, and else statements are the foundation of decision-making in Python. They allow your programs to react to different situations and make your code dynamic and powerful. Practice using these statements in your projects to master Python's conditional logic!
if, elif, and else.
Comments
Post a Comment