Python Control Flow: if-elif-else

Python if-elif-else Interview Questions

What is the basic syntax of if statement in Python?
if condition: # code to execute if condition is True
The condition can be any expression that evaluates to True or False. Python uses indentation (usually 4 spaces) to define the code block.
What is if-else statement in Python?
if condition: # code if condition is True else: # code if condition is False
The else block executes when the if condition is False. Only one of the blocks will execute.
What is elif (else if) ladder in Python?
if condition1: # code if condition1 is True elif condition2: # code if condition2 is True elif condition3: # code if condition3 is True else: # code if all conditions are False
elif allows checking multiple conditions. Python checks conditions in order and executes the first True block.
What is nested if statement in Python?
if outer_condition: # outer block if inner_condition: # inner block else: # inner else block else: # outer else block
An if statement inside another if statement. Useful for checking multiple conditions hierarchically.
What is the difference between if-elif-else and multiple if statements?
# if-elif-else (mutually exclusive) if x > 10: print(">10") elif x > 5: print(">5") # Only checks if x <= 10 # Multiple if (independent) if x > 10: print(">10") if x > 5: print(">5") # Checks regardless of previous condition
In if-elif-else, only one block executes. With multiple ifs, all True conditions execute.
What are truthy and falsy values in Python conditions?
Python treats non-boolean values as True or False in conditions:
# Falsy values: False, 0, 0.0, "", [], (), {}, None # Truthy values: Everything else if 0: # False print("0 is truthy") if 1: # True print("1 is truthy") if "hello": # True print("Non-empty string is truthy") if "": # False print("Empty string is falsy")
What is the ternary operator (conditional expression) in Python?
# Syntax: value_if_true if condition else value_if_false # Traditional if-else if age >= 18: status = "adult" else: status = "minor" # Ternary operator status = "adult" if age >= 18 else "minor" # Can be nested (but avoid for readability) result = "positive" if x > 0 else ("zero" if x == 0 else "negative")
How to check multiple conditions in one if statement?
Use logical operators: and, or, not
# AND operator (both must be True) if age >= 18 and has_license: print("Can drive") # OR operator (at least one True) if grade == 'A' or grade == 'B': print("Good grade") # NOT operator if not is_raining: print("Go outside") # Combined if (age >= 18 or with_parent) and has_ticket: print("Can enter")
What is pass statement in if blocks?
# pass is a null operation - does nothing # Used as a placeholder for empty blocks if x > 10: pass # TODO: implement later else: print("x is 10 or less") # Without pass, you'd get IndentationError # if x > 10: # # empty block - ERROR! # else: # print("x is 10 or less")
pass is useful when you need the structure but not the implementation yet.
How to write one-line if statements?
# Simple if (not recommended for complex logic) if x > 0: print("Positive") # if-else with ternary operator result = "Even" if x % 2 == 0 else "Odd" # Multiple statements with semicolon (not recommended) if x > 0: print("Positive"); x += 1 # Better approach for multiple statements if x > 0: print("Positive") x += 1
One-line if is only for very simple cases. Use multi-line for readability.
What is the difference between = and == in if conditions?
# = is assignment operator x = 5 # assigns value 5 to x # == is equality comparison operator if x == 5: # checks if x equals 5 print("x is 5") # Common mistake if x = 5: # SyntaxError! Can't assign in condition print("This won't work") # Walrus operator (Python 3.8+) allows assignment in conditions if (n := len(data)) > 10: print(f"Data has {n} items")
= assigns values, == compares values.
How to check if a value is in a range using if?
# Method 1: Using and operator if x >= 1 and x <= 10: print("x is between 1 and 10") # Method 2: Chained comparisons (Python specific) if 1 <= x <= 10: print("x is between 1 and 10") # Method 3: Using range() function if x in range(1, 11): # 11 because range is exclusive print("x is between 1 and 10") # For float ranges if 1.5 <= x <= 9.5: print("x is between 1.5 and 9.5")
Python supports chained comparisons: a < b < c
What is the difference between if-elif and if-if?
# if-elif (mutually exclusive) score = 85 if score >= 90: grade = 'A' elif score >= 80: # Only checked if score < 90 grade = 'B' # This executes for score=85 elif score >= 70: # Only checked if score < 80 grade = 'C' # if-if (independent checks) if score >= 90: grade = 'A' if score >= 80: # Always checked grade = 'B' # This ALSO executes for score=85 if score >= 70: # Always checked grade = 'C' # This ALSO executes for score=85
With if-elif, grade would be 'B'. With if-if, grade would be 'C' (last assignment).
How to use if with lists, tuples, or dictionaries?
# Check if list is empty or not my_list = [1, 2, 3] if my_list: # Truthy if list has elements print("List is not empty") # Check if element exists in list if 2 in my_list: print("2 is in the list") # Check dictionary keys my_dict = {'a': 1, 'b': 2} if 'a' in my_dict: print("Key 'a' exists") # Check dictionary values if 1 in my_dict.values(): print("Value 1 exists") # Check tuple (same as list) my_tuple = (1, 2, 3) if 3 in my_tuple: print("3 is in tuple")
What is short-circuit evaluation in if conditions?
Python stops evaluating logical expressions as soon as result is known.
# AND: stops at first False if x != 0 and y / x > 2: # Safe division print("Condition met") # If x is 0, y/x won't be evaluated # OR: stops at first True if x > 0 or y > 0 or z > 0: print("At least one is positive") # If x > 0, y>0 and z>0 won't be evaluated # Real-world example if lst and lst[0] == 'key': # Safe index access print("First element is 'key'") # If lst is empty, lst[0] won't be evaluated
How to write complex nested if-else statements?
# Example: Grading system with multiple criteria score = 85 attendance = 90 if score >= 90: if attendance >= 90: grade = 'A+' else: grade = 'A' elif score >= 80: if attendance >= 80: grade = 'B+' else: grade = 'B' elif score >= 70: grade = 'C' else: if attendance < 50: grade = 'F (Failed due to low attendance)' else: grade = 'D' print(f"Final grade: {grade}")
Keep nested ifs shallow (2-3 levels max) for readability.
What is the difference between if not and != ?
# != checks inequality if x != 0: # True if x is not equal to 0 print("x is not zero") # not negates a boolean expression if not x == 0: # Same as above print("x is not zero") # not works with truthy/falsy values if not lst: # True if lst is empty (falsy) print("List is empty") # Common patterns if not name: # Check if string is empty print("Name is required") if not found: # Check if boolean is False print("Item not found") if x is not None: # Check if not None print("x has a value")
Use != for specific value comparison, not for truthiness checks.
How to use if with try-except blocks?
# Example: Safe division with multiple checks try: result = x / y except ZeroDivisionError: print("Cannot divide by zero") except TypeError: print("Invalid types for division") else: # Executes if no exception if result > 0: print("Positive result") elif result < 0: print("Negative result") else: print("Result is zero") finally: print("Division attempt complete") # Alternative: Check before dividing if y != 0: result = x / y if result > 0: print("Positive result") else: print("Cannot divide by zero")
What are common mistakes with Python if statements?
# 1. Using = instead of == # if x = 5: # SyntaxError # 2. Missing colon # if x > 5 # SyntaxError: missing : # 3. Incorrect indentation if x > 5: print("x > 5") # IndentationError # 4. Comparing different types if "5" == 5: # False, string vs int print("This won't print") # 5. Using is for value comparison if x is 5: # Wrong for integers (works for small ints due to caching) print("Use == for value comparison") # 6. Forgetting parentheses in complex conditions if x > 5 and y < 10 or z == 0: # Ambiguous # Better: if (x > 5 and y < 10) or z == 0:
How to optimize if-elif-else chains?
# Instead of long if-elif chains: if status == "new": process_new() elif status == "pending": process_pending() elif status == "approved": process_approved() elif status == "rejected": process_rejected() else: process_default() # Use dictionary dispatch (more Pythonic) def process_new(): return "Processing new" def process_pending(): return "Processing pending" def process_approved(): return "Processing approved" def process_rejected(): return "Processing rejected" def process_default(): return "Default processing" processors = { "new": process_new, "pending": process_pending, "approved": process_approved, "rejected": process_rejected } result = processors.get(status, process_default)() print(result)
For many conditions, consider using dictionaries or match-case (Python 3.10+).
Why is if not x different from if x is False?

not x treats empty containers, zero, None, and False as falsey. x is False only matches the singleton False—stricter and rarely what you want unless enforcing booleans.

What does x or y return—not always True/False?

First truthy operand, else last (possibly non-boolean). Example: 0 or 55. Useful defaults: name = user or "guest".

Trap: if value = 3:—why error?

Assignment is a statement, not an expression (until Python 3.8+ walrus := in limited contexts). Classic syntax error—use == for comparison or walrus inside parentheses where allowed.

When does an empty elif chain fall through?

If no branch matches and no else, nothing runs—often a silent bug. Cover residual cases explicitly or assert exhaustiveness for enums.

Why prefer elif over sequential ifs?

elif stops after first match—sequential ifs might evaluate multiple branches unintentionally and waste work.

Truthiness of Decimal('0')?

Falsy like zero floats—Decimal normalizes zero to falsey context. Always understand custom numeric types’ __bool__ behavior.

What breaks if you compare floats with == in conditionals?

Rounding noise: use math.isclose or tolerances. Equality checks on computed floats often fail unexpectedly.

Nested if: how to reduce cognitive load?

Flatten with guards (if not valid: return), combine booleans, or extract helpers. Deep nesting hides bugs and hurts testing.

match/case (3.10+): gotcha with capture patterns?

Names in patterns bind—order matters; use literals vs guards (case x if ...) to avoid accidental rebinding. Study PEP 634 patterns carefully.

Why avoid mutable defaults like def f(x, seen=[])?

Same list reused across calls—conditions depending on seen become wrong. Use None sentinel and assign inside.

Does if A or B evaluate B when A is true?

No—short-circuit skips B. Don’t rely on side effects in B when A might succeed.

Ternary: a if cond else b—evaluation order?

Only one branch executes—a or b is chosen after cond evaluates. Unlike C’s comma tricks, cleaner for simple assignments.

Why might if key in dict: differ from dict.get(key)?

in checks keys only; falsy values stored require distinguishing missing vs falsey—use key in dict plus value check or dict.get(key, sentinel).

Exception vs conditional for flow control?

Exceptions should be exceptional—don’t use try/except for normal branching (slow, hides bugs). Prefer explicit tests like presence checks.

assert in production conditionals—risk?

Python can strip asserts with -O—never rely on assertions for security or essential validation; use real checks.

Chained comparison: x == y == z when y is computed twice?

Middle operand reused—still evaluated once per semantics but expressed twice conceptually; identical to (x==y) and (y==z).

Why test isinstance(x, (A, B)) vs separate ifs?

Cleaner union type checks—one branch handles multiple acceptable classes without duplication.

# Preferred: single branch for several types
if isinstance(x, (A, B)):
    handle_union(x)

# Verbose: duplicated bodies or repeated logic
if isinstance(x, A):
    ...
elif isinstance(x, B):
    ...
Bug pattern: if flag == True?

Comparing to True is redundant and can mis-handle truthy values that are not the bool True.

# Avoid
if flag == True:
    ...

# Prefer (idiomatic truthiness)
if flag:
    ...

Worse: code like if flag is True only passes for the exact singleton; truthy values such as 1 behave differently under == True vs plain if flag.

Pattern guard with regex—why raw string?

Raw literals keep backslashes single in source—easier to read and harder to get wrong when building regex strings.

import re

pattern = r"\d+"      # one backslash in source → \d in regex
# vs
pattern = "\\d+"      # same effect, easier to miscount slashes
Dead code after return in same block?

Unreachable—linters flag it. Python doesn’t warn at runtime; testing misses behaviors hidden below returns.

while True: break vs condition in while?

Both valid—sometimes mid-loop checks need break; avoid redundant flags that obscure exit conditions.

Why duplicate condition if x > 0: ... if x > 0: risky?

Second check redundant unless x mutated—signals refactor opportunity or logic bug.

Locale-aware string comparisons in conditionals?

Default unicode compares code points—not linguistically equal. Use locale or casefold() for user-facing equality rules.

Switching on types—anti-pattern?

Prefer polymorphism or singledispatch—long type-if chains resist extension and violate open/closed principle.

if __debug__: purpose?

False-like when running with -O—gate expensive diagnostic branches without runtime cost in optimized builds.

Why document complex boolean expressions?

Named booleans (valid_age = ...) communicate intent—reduces mis-parenthesizing in interviews and reviews.

Trap: relying on evaluation order in comprehensions with side effects?

CPython order is predictable but side-effectful filters are fragile—keep comprehensions pure for clarity.

Checking membership of large list vs set?

in list is O(n); convert to set once if repeated checks—conditional-heavy loops bottleneck here.

Final edge: if a < b > c valid?

Yes—means a < b and b > c; useful for “b is strictly between” style checks without repeating b.

Note: These questions cover Python's conditional statements (if, if-else, elif ladder, nested if). Remember: Python uses indentation for code blocks, supports chained comparisons (a < b < c), and has truthy/falsy values. For complex conditional logic, consider using dictionary dispatch or match-case statements (Python 3.10+). Always prioritize readability over cleverness.
Prev: Operators Python Control Flow (if-elif-else) Next: Loops