Python Conditional Statements: if,else and elif

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 >= 18 is the condition.
  • If it's True, the first block runs.
  • If it's False, the else block 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-else chain.
  • 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:


๐Ÿ“Œ Bookmark this blog or follow for updates!

Python Logo

๐Ÿ‘ Liked this post? Share it with friends or leave a comment below!

Previous Post Next Post

Contact Form