Python Conditional Statements: if, else, and elif Explained
1. ๐ง What is if-else in Python?
In Python, if and else are used to make decisions. You can check a condition and run a block of code depending on whether it’s True or False.
๐ค Syntax:
if condition:
# code to run if condition is True
else:
# code to run if condition is False
Example 1: Basic if-else
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output:
You are an adult.
๐ How it works:
age >= 18is the condition.- If it's
True, the first block runs. - If it's
False, theelseblock runs.
2. ๐ค Why Do We Need elif?
Sometimes you want to check multiple conditions — not just one or two. This is where elif (short for "else if") becomes useful.
๐ Example Situation:
Let’s say you want to check if a number is positive, negative, or zero.
3. ๐ช Using if-elif-else
๐ค Syntax:
if condition1:
# run if condition1 is True
elif condition2:
# run if condition2 is True
elif condition3:
# run if condition3 is True
else:
# run if all above conditions are False
Example 2: Check if number is positive, negative, or zero
num = 0
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
Zero
๐ How it works:
- The code checks
num > 0. If True, it prints "Positive number". - If not, it checks
num == 0. If True, it prints "Zero". - If both conditions are False, it goes to
else.
4. ๐งช More Real-World Example: Grading System
marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: A
5. ⚠️ Caution:
- Only one block of code will run in an
if-elif-elsechain. - Python checks conditions from top to bottom and stops when one is True.
6. ✅ Summary Table
| Keyword | Use | Can be repeated? |
|---|---|---|
if |
First condition to check | Only once |
elif |
More conditions to check if previous ones failed | Yes, multiple times |
else |
Runs if all other conditions are False | Only once at the end |
๐ Final Tip:
Use if-else for two-way decisions, and if-elif-else when you have three or more cases to check. It makes your code cleaner and avoids writing many nested if statements.
Hope this clears your confusion on Python conditions! ๐๐ง
๐ Practice Questions:
๐ Related Topics:
- ➤ Python Arithmetic Operators
- ➤ Basic String Functions
- ➤ Advanced String Functions
- ➤ Basic List Functions
- ➤ Advanced List Functions : Part-1
- ➤ Advanced List Functions : Part-2
- ➤ Basic Tuple Functions
- ➤ Advanced Tuple Functions
- ➤ Basic Dictionary Functions
- ➤ Advanced Dictionary Functions
- ➤ Conditional Statements : if-elif-else
- ➤ Python 'for' Loop
- ➤ Python 'while' Loop
- ➤ Difference between 'for' loop and 'while' loop
- ➤ Introducing Python Functions
๐ Bookmark this blog or follow for updates!
๐ Liked this post? Share it with friends or leave a comment below!