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+).
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.