Python Control Flow (if-else, switch) Exercises
Python Control Flow (if-else, switch) Practice Questions
Which of the following statements is true about an if statement in Python?
- An
ifstatement 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
elseblock executes when theifcondition evaluates to False.
Example:
x = 3
if x > 5:
print("Greater than 5")
else:
print("5 or less")
Output:
5 or less
- Option 1:
elifis used for additional conditional checks afterif. - Option 2:
thenis not a Python keyword. - Option 3:
switchis not a Python keyword; Python usesmatch-casein 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 = 7and the conditionx < 5is False.- The
elseblock runs when theifcondition 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 operators
and,or,notto combine multiple conditions. - Option 1 correctly checks that both
x > 5andy < 10are True. - Option 2:
thenis not a valid keyword in Python. - Option 3: Syntax is incorrect (
orneeds another condition). - Option 4: Comma cannot combine conditions in
ifstatements.
What will be the output of the following code?
x = 10
if x % 2 == 0:
print("Even")
else:
print("Odd")
x = 10,x % 2 == 0evaluates to True because 10 is divisible by 2.- The
ifblock 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 conditionx > 10is True → enter firstifblock.- Inner
if x % 2 == 0:15 % 2 = 1→ False → executeelse→ prints"Odd and greater than 10". - Option 1: False — 15 is not even.
- Option 3: False —
xis 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 > 5is Truey = 12→y < 10is Falseif x > 5 and y < 10→ True and False = False → skip first blockelif 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 eachcasein order:-
case 1: False → skip -
case 2: False → skip -
case 3: True → executeprint("Wednesday")
-
-
The
_case acts as a default (likeelseordefaultin other languages). -
Output: Wednesday
-
Option 1 & 2: Incorrect →
daydoesn’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
casein order:case 10 | 9: False → skipcase 8: True → executesprint("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 >= 90condition is checked.score = 92, so this is True.- Python executes
print("Excellent")and skips the else block entirely.
- The
match-caseinsideelseis ignored because theifcondition already ran. - Output:
Excellent
Quick notes:
- Option 1 & 2: Wrong →
elseblock is not executed. - Option 4: Wrong → default case in match-case is skipped.
- This shows that if-else takes priority, and
match-caseruns only if theelseblock 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 < 18is False → skip firstif. -
Enter the
elseblock:-
income < 30000→ 50000 < 30000? False → skip -
income <= 70000→ 50000 <= 70000? True → executeprint("Adult with Medium income")✅
-
-
The last
elseis 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:
-
Step 1:
day = 5 -
Step 2: Python checks each
casein order:-
case 1 | 2 | 3 | 4 | 5→ True (5 matches) → executeprint("Weekday")✅ -
Remaining cases are skipped.
-
-
Key points:
-
|allows multiple values in a single case. -
_acts as a default for unmatched values. -
Output:
Weekday
-
-
Option 1: Incorrect → 5 is not 6 or 7
-
Option 3: Incorrect → default only triggers if no match
-
Option 4: Incorrect → no syntax error
What will be the output of the following code?
x = 12
y = 7
z = 5
if x > 10 and (y < 10 or z > 10):
print("Condition Met")
else:
print("Condition Not Met")
The code uses if with nested logical operators to decide the output:
- Step 1: Evaluate
x > 10→ 12 > 10 → True - Step 2: Evaluate the expression inside parentheses:
y < 10 or z > 10y < 10→ 7 < 10 → Truez > 10→ 5 > 10 → False- Result of
y < 10 or z > 10→ True or False → True
- Step 3: Combine with
and: True and True → True - Step 4: The
ifblock executes → prints "Condition Met"
Summary:
- Nested logical operators allow complex decision-making.
- Option 1: Incorrect → condition is actually True.
- 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
ifblock and checkhumidity > 70→ 80 > 70 → True - Step 3: Since both conditions are True, the code executes
print("Hot and Humid") - Step 4: The
elifandelseblocks are skipped because the firstifran.
Key Points:
- Nested if-else allows checking multiple related conditions in sequence.
- Outer
ifdetermines the main category (temperature). - Inner
ifhandles 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 <= 60ensures the age is between 18 and 60, inclusive. - Step 2: The
and has_idpart ensures the person must have a valid ID. - Step 3: Option 3 correctly combines both conditions using
andand Python’s chained comparison for readability.
Why other options are incorrect:
- Option 1: Uses
orincorrectly → 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 →
ormakes 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. - Step 2:
case 1 | 2 | 3 | 4 | 5→ False → skip - Step 3:
case 6 | 7→ True → executeprint("Weekend")
Why other options are incorrect:
- Option 1:
6 & 7is invalid syntax for matching multiple values. - Option 3:
6 or 7does 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 oforis 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 → executeprint("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-casedoes not allow relational expressions like90 <= score <= 100directly - Option 4: Order matters → using
score > 100first 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 oforis 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
andandorwithout parentheses → condition fails for some valid scenarios. - Option 3: Membership is False → inner
andevaluates 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 oforis 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
andandor→ fails in some valid scenarios. - Option 3: Clearance = 4 → inner
andevaluates 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.
Explore More Python Exercises
You may also like these Python exercises:
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 (if-else, switch)
When we write programs, it’s not enough to just run code in a straight line. We need ways to make decisions, to tell the program what to do depending on the situation. That’s where control flow comes in, and in this section on Solviyo, we’ll be focusing on if-else statements and Python’s version of switch-like logic.
Let’s start with the basics. The if statement is your go-to tool for decision making. It checks a condition, and if it’s true, it runs the code you tell it to. Add an else and you’ve got a fallback for when the condition doesn’t match. Throw in an elif, and you can cover multiple possibilities. In these exercises, you’ll try out all of these, beginning with simple checks like “is a number positive or negative?” and then moving into trickier situations with multiple branches and nested conditions.
Now, what about the switch statement? In some languages, it’s built-in, but Python doesn’t have one. Don’t worry—we’ll show you how to achieve the same idea in a more Pythonic way. You’ll practice using dictionaries, functions, and even the newer pattern matching to replace switch cases. It’s a neat skill that makes your code cleaner and much easier to maintain.
Throughout this section, we’ve built exercises that feel close to real life. Think about assigning grades based on marks, building a simple calculator, or writing a menu-driven program where the user picks an option. These aren’t just random coding drills—they’re examples you can actually connect to. And by solving them, you’ll see how powerful control flow is when it comes to shaping the logic of your programs.
At Solviyo, we don’t just throw problems at you—we guide you through them. Every exercise is designed to make you think, and once you solve it, you’ll understand the “why” behind the answer. We’ll also point out some common mistakes, like forgetting to add a default case or making conditions too complicated, so you don’t repeat them in your own code.
By the time you finish this section, you’ll be confident with using if-else logic and Python’s alternatives to switch. More importantly, you’ll know how to use these tools in real coding projects. So let’s dive in and practice—because the best way to get good at control flow is by writing and testing your own code.