Python Control Flow (if-else, switch) Practice Questions
Correct
0%
Which of the following statements is true about an if statement in Python?
An if statement is a conditional statement.
It evaluates the given condition:
If True, the indented block of code runs.
If False, the code block is skipped.
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
Option 2: Incorrect, ignores the condition.
Option 3: False — that would be handled by else.
Option 4: Incorrect — repeating code is done using loops (for, while).
Which keyword is used in Python to execute a block of code when the if condition is not met?
The else block executes when the if condition evaluates to False.
Example:
x = 3
if x > 5:
print("Greater than 5")
else:
print("5 or less")
Output:
5 or less
Option 1:elif is used for additional conditional checks after if.
Option 2:then is not a Python keyword.
Option 3:switch is not a Python keyword; Python uses match-case in 3.10+ or if-elif chains.
What will be the output of the following code?
x = 7
if x < 5:
print("Less than 5")
else:
print("5 or more")
x = 7 and the condition x < 5 is False.
The else block runs when the if condition is False.
Output: 5 or more
Option 1: Wrong — condition is not met.
Option 2: Wrong — print(x) is not used.
This illustrates basic if-else branching.
Option 4: No error occurs; syntax is correct.
Which of the following is the correct way to check multiple conditions in Python?
Python uses logical operatorsand, or, not to combine multiple conditions.
Option 1 correctly checks that bothx > 5andy < 10 are True.
Option 2:then is not a valid keyword in Python.
Option 3: Syntax is incorrect (or needs another condition).
Option 4: Comma cannot combine conditions in if statements.
What will be the output of the following code?
x = 10
if x % 2 == 0:
print("Even")
else:
print("Odd")
x = 10, x % 2 == 0 evaluates to True because 10 is divisible by 2.
The if block executes and prints "Even".
Option 1: Wrong — condition is True, not False.
Option 2: Wrong — code does not print x.
Option 4: Wrong — no syntax error occurs.
What will be the output of the following code?
x = 15
if x > 10:
if x % 2 == 0:
print("Even and greater than 10")
else:
print("Odd and greater than 10")
else:
print("10 or less")
x = 15 → outer condition x > 10 is True → enter first if block.
Inner if x % 2 == 0: 15 % 2 = 1 → False → execute else → prints "Odd and greater than 10".
Option 1: False — 15 is not even.
Option 3: False — x is greater than 10.
Option 4: No error occurs; syntax is correct.
What will be the output of the following code?
x = 7
y = 12
if x > 5 and y < 10:
print("Condition A")
elif x > 5 or y < 10:
print("Condition B")
else:
print("Condition C")
x = 7 → x > 5 is True
y = 12 → y < 10 is False
if x > 5 and y < 10 → True and False = False → skip first block
elif x > 5 or y < 10 → True or False = True → execute second block → prints "Condition B"
Option 1: False — first condition not satisfied.
Option 3: False — second condition satisfied.
Option 4: No syntax error occurs.
What will be the output of the following code?
day = 3
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case _:
print("Other day")
day = 3, so Python checks each case in order:
case 1: False → skip
case 2: False → skip
case 3: True → execute print("Wednesday")
The _ case acts as a default (like else or default in other languages).
Output: Wednesday
Option 1 & 2: Incorrect → day doesn’t match 1 or 2
Option 4: Incorrect → _ case only executes if no other match
What will the following code print?
score = 85
match score // 10:
case 10 | 9:
print("Grade A")
case 8:
print("Grade B")
case 7:
print("Grade C")
case _:
print("Grade D")
The code uses Python’s match-case to assign grades:
score // 10 = 85 // 10 = 8
Python checks each case in order:
case 10 | 9: False → skip
case 8: True → executes print("Grade B")
_ acts as a default case for all unmatched values.
Summary:
Output: Grade B
Other options:
Option 1: False → 10 or 9 only
Option 3: False → 7 only
Option 4: False → default only executes if no match
What will the following code print?
score = 92
if score >= 90:
print("Excellent")
else:
match score // 10:
case 8:
print("Very Good")
case 7:
print("Good")
case _:
print("Average")
Explanation detail The code uses if-else combined with match-case to decide the output:
First, the if score >= 90 condition is checked.
score = 92, so this is True.
Python executes print("Excellent") and skips the else block entirely.
The match-case inside else is ignored because the if condition already ran.
Output:Excellent
Quick notes:
Option 1 & 2: Wrong → else block is not executed.
Option 4: Wrong → default case in match-case is skipped.
This shows that if-else takes priority, and match-case runs only if the else block is reached.
What will be the output of the following code?
age = 25
income = 50000
if age < 18:
print("Minor")
else:
if income < 30000:
print("Adult with Low income")
elif income <= 70000:
print("Adult with Medium income")
else:
print("Adult with High income")
First, age = 25 → age < 18 is False → skip first if.
Enter the else block:
income < 30000 → 50000 < 30000? False → skip
income <= 70000 → 50000 <= 70000? True → execute print("Adult with Medium income") ✅
The last else is ignored because one condition matched.
Key points:
Nested if-else allows decision making on multiple variables.
The code first checks age, then income for adults.
Output: Adult with Medium income.
What will the following code print?
day = 5
match day:
case 1 | 2 | 3 | 4 | 5:
print("Weekday")
case 6 | 7:
print("Weekend")
case _:
print("Invalid day")
The code uses Python’s match-case (switch-style) to classify days:
Option 2 & 4: Incorrect → syntax is valid and code prints output.
What will be the output of the following code?
temperature = 35
humidity = 80
if temperature > 30:
if humidity > 70:
print("Hot and Humid")
else:
print("Hot but Comfortable")
elif temperature > 20:
print("Warm")
else:
print("Cool")
This code demonstrates nested if-else statements to determine weather conditions:
Step 1: Check temperature > 30 → 35 > 30 → True
Step 2: Enter the first if block and check humidity > 70 → 80 > 70 → True
Step 3: Since both conditions are True, the code executes print("Hot and Humid")
Step 4: The elif and else blocks are skipped because the first if ran.
Key Points:
Nested if-else allows checking multiple related conditions in sequence.
Outer if determines the main category (temperature).
Inner if handles secondary factors (humidity).
Output: Hot and Humid
Which code snippet correctly prints "Eligible" only if a person is between 18 and 60 years old, inclusive, and has a valid ID?
This question demonstrates a tricky conditional expression to check eligibility based on age and ID:
Step 1: The condition 18 <= age <= 60 ensures the age is between 18 and 60, inclusive.
Step 2: The and has_id part ensures the person must have a valid ID.
Step 3: Option 3 correctly combines both conditions using and and Python’s chained comparison for readability.
Why other options are incorrect:
Option 1: Uses or incorrectly → a person without ID could still pass if age condition is met.
Option 2: Excludes 18 and 60 due to strict > and < operators.
Option 4: Misuses operator precedence → or makes the condition always True for many cases.
Key takeaway: Use parentheses or chained comparisons to combine multiple conditions correctly and avoid logical errors.
Which snippet correctly prints "Weekend" for day values 6 or 7, and "Weekday" otherwise?
This code demonstrates Python’s match-case to differentiate weekdays and weekends:
Step 1:day = 7, so Python checks each case in order.
Option 1:6 & 7 is invalid syntax for matching multiple values.
Option 3:6 or 7 does not work as expected in match-case; evaluates incorrectly.
Option 4: Uses default _, which would incorrectly classify all days not 1-5 as "Weekend".
Key takeaway: Use | in match-case for multiple specific matches; do not confuse with or or &.
Which snippet will print "Access Granted"only if the user is an admin or has both a key and password?
This code demonstrates complex logical conditions to control access:
Step 1:is_admin = False, so the first part of or is False.
Step 2: Evaluate the parentheses: has_key and has_password → True and True → True
Step 3: Combine with or: False or True → True
Step 4:print("Access Granted") executes ✅
Why other options are incorrect:
Option 2:has_password = False → condition evaluates to False → no access.
Option 3: Logical operators do not match the requirement; would give wrong results for some users.
Option 4: Condition misuses parentheses → gives True for some invalid cases.
Key takeaway: Use parentheses to group logical conditions correctly; this ensures the intended precedence of and and or.
Which snippet correctly prints "Grade A" for scores 90–100, "Grade B" for 80–89, and "Invalid" for scores above 100 or below 0?
This example demonstrates a match-case structure with a default case for invalid input:
Step 1:score = 105
Step 2: Python checks each case in order:
Cases 90–100 → False
Cases 80–89 → False
Default case _ → True → execute print("Invalid")
Step 3: Output is Invalid
Why other options are incorrect:
Option 2: No default case → code would do nothing for score = 105
Option 3: Python match-case does not allow relational expressions like 90 <= score <= 100 directly
Option 4: Order matters → using score > 100 first is tricky, could be confusing; Option 1 is cleaner and explicit
Key takeaway: Use explicit matches for discrete values and a default _ case to handle invalid inputs clearly in match-case.
Which snippet prints "Special Discount" only if a customer is loyal or has a purchase above 1000 and membership active?
This code demonstrates a tricky combination of logical operators with nested conditions to determine discount eligibility:
Step 1:loyal = False, so first part of or is False.
Step 2: Evaluate parentheses: purchase > 1000 and membership → 1200 > 1000 and True → True
Step 3: Combine with or: False or True → True
Step 4:print("Special Discount") executes
Why other options are incorrect:
Option 2: Uses and and or without parentheses → condition fails for some valid scenarios.
Option 3: Membership is False → inner and evaluates to False → no discount.
Option 1: Parentheses misplace precedence → some loyal customers without active membership would fail incorrectly.
Key takeaway: Always use parentheses to clearly define precedence in complex logical conditions combining and and or.
Which snippet prints "Valid Access"only if a user is either an admin, or a manager with clearance level above 5?
This question tests understanding of logical operator precedence in combined conditions:
Step 1:is_admin = False → first part of or is False
Step 2: Evaluate parentheses: is_manager and clearance > 5 → True and 6 > 5 → True
Step 3: Combine with or: False or True → True
Step 4:print("Valid Access") executes
Why other options are incorrect:
Option 2: Logical expression incorrectly combines and and or → fails in some valid scenarios.
Option 3: Clearance = 4 → inner and evaluates to False → no access.
Option 4: Parentheses change precedence → would incorrectly require clearance > 5 for admins too.
Key takeaway: Parentheses are crucial to ensure correct evaluation order when combining and and or in access control logic.
Quick Recap of Python Control Flow (if-else, switch) Concepts
If you are not clear on the concepts of Control Flow (if-else, switch), you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
Python Control Flow — if, elif, else, and match
Control flow in Python allows your programs to make decisions and execute different blocks of code based on conditions. Using statements like if, elif, else, and the newer match statement, you can handle multiple scenarios, process input intelligently, and control how your program responds to different situations.
Understanding control flow is essential for writing programs that can respond dynamically, process data intelligently, and behave differently based on user input or internal logic.
Conditional Statements: if, elif, else
These statements allow your Python program to make decisions based on conditions.
Statement
Purpose
Typical Use Case
if
Executes a block if the condition is True
Basic decision-making, e.g., “is a number positive?”
elif
Executes another block if previous if/elif conditions were False
Multiple related checks, e.g., grading or category assignment
else
Executes if all previous conditions were False
Default or fallback case
Example:
age = 18
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
Python Alternatives to Switch Statements
Python does not have a traditional switch … case statement. Similar behavior can be achieved with:
if / elif / else chains — simple and widely used.
match / case statement (Python 3.10+) — pattern matching for cleaner, maintainable code.
Dictionary mapping or function dispatching — maps input values to functions or outcomes.
Example using match:
value = 2
match value:
case 1:
print("Option 1 selected")
case 2:
print("Option 2 selected")
case _:
print("Default option")
Common Pitfalls and Best Practices
Tip
Explanation
Indentation
Incorrect indentation can break logic or execute unintended code.
Use elif
Instead of multiple independent if statements for the same variable — avoids unnecessary checks.
Use else as default
Always place else after all if and elif blocks.
Consider match or dictionary mapping
For multiple discrete values, these improve readability and maintainability compared to long if/elif chains.
Test conditions carefully
Ensures logic works as intended, especially in nested or complex conditions.
Why Control Flow Is Important
Without control flow, programs execute sequentially with no decisions or flexibility.
Control flow enables dynamic behavior, allowing programs to react to user input or internal data.
Clear use of if, elif, else, and match makes code readable and easier to maintain.
Mastering control flow is essential before learning advanced topics like loops, functions, and exception handling.
Test Your Python Control Flow (if-else, switch) Knowledge
Practicing Python Control Flow (if-else, switch)? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python Control Flow Exercises
Welcome to Solviyo’s Python Control Flow exercises, where you will learn how to guide your program’s logic using if-else statements and Pythonic alternatives to switch-case. Control flow is essential for making decisions in your code, allowing programs to respond differently depending on conditions. These exercises are designed to help you master decision-making structures in Python from the basics to practical, real-world applications.
What You Will Learn
In this set of Python Control Flow exercises, you will explore:
Using if, elif, and else statements to handle multiple conditions.
Writing nested conditions for complex decision-making scenarios.
Implementing switch-like logic in Python using dictionaries, functions, and pattern matching.
Applying control flow to real-world problems, such as grade calculation, menu-driven programs, and simple calculators.
Identifying and avoiding common mistakes in decision structures.
Writing clean, maintainable, and efficient control flow code.
Why Learning Python Control Flow Matters
Control flow is a fundamental concept in Python programming. Mastering if-else statements and alternatives to switch allows you to create programs that can make intelligent decisions, respond to user input, and adapt to different situations. Understanding control flow is also crucial for advanced programming topics, problem-solving, and coding interviews.
Start Practicing Python Control Flow Today
By completing these exercises, you will gain confidence in implementing decision-making logic in Python. Each exercise includes detailed explanations to help you understand the reasoning behind solutions and avoid common pitfalls. Start practicing Python Control Flow exercises now, and build a strong foundation for writing logical, interactive, and dynamic Python programs.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.