0%

18- Conditional Statements (if / elif / else)

Make decisions in your code. Choose different paths based on conditions. The most important control structure in programming.

Your program reaches a fork in the road. To the left, one path. To the right, another. Which way should it go? The answer depends on a condition. Is the user logged in? Is the score high enough? Is the file open? Conditional statements are how Python makes decisions. They allow your program to choose different actions based on different situations. Without conditionals, every program would be a straight line. With conditionals, programs become flexible, responsive, and intelligent. Python provides three keywords for conditionals: if, elif (short for “else if”), and else. Together, they create decision trees that can handle any number of possibilities.

🕯️ Magic Note

The word elif is unique to Python. Other languages use else if (two words) or elsif or elif (Perl). Python chose elif because it is short, clear, and consistent with the indentation-based syntax. No braces. No end if. Just elif and proper indentation.

The if Statement (The Single Path)
The simplest conditional. If the condition is True, execute the indented block. If False, skip it entirely.

Python

temperature = 30

if temperature > 25:

print(“It is a hot day”)

print(“Drink water”)

print(“This runs always”)

💡 The colon : at the end of the if line is required. The indented block can contain one or more statements. Use 4 spaces for indentation (PEP 8 standard).
The if-else Statement (Two Paths)
One path for when the condition is True. Another path for when it is False. Two possibilities. Two outcomes.

Python

age = 16

if age >= 18:

print(“You can vote”)

else:

print(“You are too young to vote”)

🕯️ Magic Note

The else clause catches everything that the if condition does not catch. It is the “otherwise” of your decision. No condition needed after else. Just a colon and an indented block.

The if-elif-else Statement (Multiple Paths)
For three or more possibilities, use elif. Python checks each condition in order. The first condition that is True runs its block. The rest are skipped. If none are true, the else block runs (if present).

Python

score = 85

if score >= 90:

grade = “A”

elif score >= 80:

grade = “B”

elif score >= 70:

grade = “C”

elif score >= 60:

grade = “D”

else:

grade = “F”

print(f”Grade: {grade}”) # Grade: B

⚠️ Order matters in if-elif-else chains. Put the most specific conditions first. If you put score >= 60 before score >= 80, a score of 85 would match the first condition and you would never reach the higher grade check.
Multiple Conditions with Logical Operators
You can combine conditions using and, or, and not. This allows complex decision logic in a single if statement.

Python

age = 25

has_license = True

is_weekend = False

# AND – both must be True

if age >= 18 and has_license:

print(“You can drive”)

# OR – at least one must be True

if is_weekend or age < 12:

print(“Special discount applies”)

# NOT – reverses the condition

if not is_weekend:

print(“It is a weekday”)

# Combining multiple operators

if (age >= 18 and has_license) and not is_weekend:

print(“You can drive to work”)

💡 Use parentheses to group complex conditions. They make your intent clear and ensure the correct order of evaluation. and has higher precedence than or, but parentheses remove any doubt.
Nested Conditionals
You can put an if statement inside another if statement. This is called nesting. Use it when a decision depends on a previous decision.

Python

is_logged_in = True

user_role = “admin”

if is_logged_in:

print(“Welcome back”)

if user_role == “admin”:

print(“You have admin privileges”)

print(“You can delete users”)

else:

print(“You are a regular user”)

else:

print(“Please log in”)

🕯️ Magic Note

Deep nesting (more than 3 levels) makes code hard to read. If you find yourself nesting too deeply, consider using elif chains or extracting logic into functions. Flat is better than nested.

Ternary Operator (Inline if-else)
For simple conditions, Python offers a one-line if-else called the ternary operator. The syntax is value_if_true if condition else value_if_false.

Python

age = 20

# Regular if-else

if age >= 18:

status = “adult”

else:

status = “minor”

# Ternary operator (one line)

status = “adult” if age >= 18 else “minor”

print(status) # adult

# Can be used inside print directly

print(“Eligible” if score >= 60 else “Not eligible”)

⚠️ Do not overuse the ternary operator. It is great for simple assignments but becomes unreadable when nested or too long. If you need multiple conditions, use a regular if-elif-else block.
Truthy and Falsy in Conditions
Python conditions do not require explicit comparisons to True or False. Any value can be used directly.

Python

# Instead of if len(name) > 0:

name = “Feloriya”

if name:

print(f”Hello {name}”) # This runs (non-empty string is truthy)

# Instead of if len(items) == 0:

items = []

if not items:

print(“The list is empty”) # This runs (empty list is falsy)

# Instead of if count != 0:

count = 5

if count:

print(f”Count is {count}”) # This runs (non-zero is truthy)

💡 Using truthiness makes your code cleaner and more Pythonic. Write if name: instead of if len(name) > 0:. Write if not items: instead of if items == []:.
Common Patterns with Conditionals
Here are patterns you will see frequently in Python code.

Python

# 1. Guard clause (early return)

def divide(a, b):

if b == 0:

return None # Guard against division by zero

return a / b

# 2. Default value assignment

user_input = input(“Enter name: “)

name = user_input if user_input else “Anonymous”

# 3. Range checking with chained comparisons

if 0 <= score <= 100:

print(“Valid score”)

# 4. Member checking

allowed_users = [“Ali”, “Sara”, “Reza”]

if username in allowed_users:

print(“Access granted”)

The pass Statement for Empty Blocks
Sometimes you need an if block but have nothing to put in it yet. Python requires at least one statement in an indented block. Use pass as a placeholder.

Python

error_code = 404

if error_code == 200:

pass # TODO: Handle success later

elif error_code == 404:

print(“Page not found”)

else:

pass # TODO: Handle other errors

🕯️ Magic Note

pass does nothing. It is a placeholder that satisfies Python’s need for an indented block. Use it when you are planning to write code later or when you need a block syntactically but not logically.

Common Mistakes with Conditionals
  • Forgetting the colon : after if, elif, or else
  • Inconsistent indentation (mixing spaces and tabs)
  • Using = instead of == in conditions if x = 5:
  • “Forgetting that elif is one word, not “else if”
  • Putting else with a condition else x > 5: (else has no condition)
  • Deep nesting that makes code unreadable
  • Comparing to True or False explicitly if is_ready == True: (just write if is_ready:)
Check Your Understanding
  • Write an if-else statement that prints “Positive” for numbers greater than 0 and “Non-positive” otherwise.
  • What is wrong with this code: if x = 5: print(“x is 5”)?
  • How do you check if a string is empty without using len()?
  • Write a ternary operator that assigns “high” if score > 80 else “low”.
  • What is the purpose of the pass statement?
  • Why does order matter in an if-elif-else chain?

⚡ Whisper

Every decision is a fork in the road. The program stands at the junction, looking left then right. It asks a question. The answer is True or False. Then it moves. This is the breath of logic. This is how code becomes alive. Without if, your program is a straight line to nowhere. With if, it can adapt. It can choose. It can respond to the user, to the data, to the world. elif adds more turns. else catches everything else. Together they form a map of possibilities. Learn to read the map. Learn to draw the forks. Every condition you write is a gift of flexibility to your program.

Related posts