Start with the study notes on Conditionals (definitions, examples and a quick revision), then work through 30 practice questions, each with the correct answer and a clear explanation of why it is right. When you are ready, take this topic as an interactive quiz to test yourself.
13 easy Β· 13 medium Β· 4 hard Β· Part of Python: Master Python from basics to advanced - 20 topics.
Topic overview
Conditionals β making decisions with if, elif and else
1. if, elif and else
An if statement runs a block only when its condition is true. elif (βelse ifβ) checks another condition, and else runs when nothing above matched. Each line ends with a colon, and the body is indented.
Python stops at the first true condition and skips the rest. Put the most specific test first.
score = 95
# Wrong order: 95 >= 60 is true first
if score >= 60:
print("C")
elif score >= 90:
print("A")
# Right order
if score >= 90:
print("A")
elif score >= 60:
print("C")
OutputC
A
Remember: Two separate if statements are both checked; an if/elif chain picks only one branch.
3. Conditions can be any value
An if works with truthiness: empty containers, 0, "" and None count as false.
items = []
if items:
print("has items")
else:
print("empty")
Outputempty
Example:if items: is the Pythonic way to check for a non-empty list, instead of len(items) > 0.
4. Combining conditions
Use and, or and not to combine conditions.
Use a chained comparison for ranges: 10 <= x <= 20.
Use in to test membership: fruit in ["apple", "mango"].
age, has_id = 20, True
if age >= 18 and has_id:
print("entry allowed")
x = 15
print(10 <= x <= 20)
print("apple" in ["apple", "mango"])
Outputentry allowed
True
True
A common bug
if age == 13 or 14 or 15: is always true, because 14 on its own is a truthy value. Write if age in (13, 14, 15): instead.
5. The conditional expression (ternary)
A conditional expression picks one of two values in a single line: A if condition else B.
age = 15
status = "adult" if age >= 18 else "minor"
print(status)
n = 7
print("even" if n % 2 == 0 else "odd")
Outputminor
odd
6. Short-circuit guards
and stops at the first false part, so you can put a safety check first.
x = 0
if x != 0 and 10 / x > 2:
print("big")
else:
print("skipped safely")
Outputskipped safely
Remember: Reversing the order (10 / x > 2 and x != 0) would crash with ZeroDivisionError when x is 0.
7. Checking for None and placeholders
Check for None with is: if result is None:.
pass does nothing. Use it as a placeholder where Python needs a block.
result = None
if result is None:
print("not found")
if True:
pass # TODO: write this later
Outputnot found
8. match / case (Python 3.10+)
match compares a value against several patterns, like a switch in other languages. case _: is the default.
command = "stop"
match command:
case "start":
print("starting")
case "stop":
print("stopping")
case _:
print("unknown")
Outputstopping
9. Comparing input
Input is text, so compare it to text, or convert it first.
age = "18" # what input() would give you
print(age == 18) # a string never equals a number
print(int(age) == 18)
OutputFalse
True
10. Common misconceptions
Misconception
Correct understanding
if x = 5: compares x with 5.
= is assignment and is a SyntaxError in a condition; use ==.
All branches of an elif chain can run.
Only the first true branch runs.
age == 13 or 14 checks two ages.
It is always true; write age in (13, 14).
"18" == 18 is True.
A string never equals a number; convert with int() first.
x == None is the best None check.
Use x is None.
11. Quick revision
if
Runs a block when a condition is true.
elif
Checks another condition if the earlier ones failed.
else
Runs when no condition matched.
Ternary
A if condition else B, in one line.
and / or / not
Combine or flip conditions.
in
Tests membership.
pass
A placeholder that does nothing.
match / case
Pattern matching, from Python 3.10.
12. Test your understanding
When does an else block run?
Show answer
When none of the if/elif conditions were true.
score = 95, and the chain checks >= 60 first. Which branch runs?
Show answer
The >= 60 branch, because it is the first true condition.
What does if []: count as?
Show answer
False, because an empty list is falsy.
Write a one-line condition that sets status to "adult" or "minor".
Show answer
status = "adult" if age >= 18 else "minor"
Why is if age == 13 or 14: always true?
Show answer
14 alone is truthy, so the or is always true.
How do you check if x is None?
Show answer
if x is None:
What does pass do?
Show answer
Nothing; it is a placeholder.
What is "18" == 18?
Show answer
False.
Key takeaway: Python picks the first true branch of an if/elif chain, so order your tests carefully, and remember that any value can act as a condition.
Notes written by Velnov. Every code example with an output was run in Python 3 to check that the output shown is exactly what Python prints.
Key concepts in this topic
IndentationColonif/else chainsif/elif/elseif vs elifelifEvaluation orderTruthinessFalsy valuesEmpty collectionsTernary expressionConditional expressionModuloEven/odd= vs ==SyntaxErrorLogical operatorsChained comparisonin operatorMembershipcontinuePlaceholdersCommon gotchasNone
B 'Else if' - test another condition when the previous ones were False
C A loop keyword
D Error handling
Answer: B β 'Else if' - test another condition when the previous ones were False
elif is short for 'else if' - it adds another condition that is only checked when all previous if/elif conditions were False. You can chain as many as you like.
if/else chains
Q3.easy
When does the else block run?
age = 15
if age >= 18:
print("Adult")
else:
print("Minor") # runs - condition was False
A Always
B Only when the if (and every elif) condition was False
C Only when the if condition was True
D Never - it's optional decoration
Answer: B β Only when the if (and every elif) condition was False
else is the catch-all: it runs exactly when none of the if/elif conditions matched. It takes no condition of its own.
if/elif/else
Q4.easy
What is the output of:
x = 7
if x > 5:
print("A")
if x > 6:
print("B")
A A
B B
C A then B
D Nothing
Answer: C β A then B
These are two SEPARATE if statements - both conditions are checked independently, and both are True (7 > 5 and 7 > 6), so both print.
With elif instead of the second if, only 'A' would print.
if vs elif
Q6.easy
What is the output of:
if 0:
print("yes")
else:
print("no")
if 0: print("never")
if 1: print("always") # any non-zero is truthy
if "hi": print("always") # non-empty string
A yes
B no
C 0
D Error
Answer: B β no
if works with any value, not just True/False. 0 is falsy, so the else branch runs. Falsy values: 0, "", [], {}, (), None, False.
TruthinessFalsy values
Q9.easy
Which condition tests whether n is an even number?
n = 8
if n % 2 == 0:
print("even") # prints
else:
print("odd")
A n % 2 == 0
B n / 2 == 0
C n % 2 == 1
D n // 2 == 0
Answer: A β n % 2 == 0
Even numbers leave remainder 0 when divided by 2, so n % 2 == 0. (n % 2 == 1 tests for ODD numbers.)
ModuloEven/odd
Q10.easy
What happens with:
if x = 5:
print("five")
if x == 5: # correct - comparison
print("five")
A Prints five when x is 5
B SyntaxError - assignment is not allowed as a condition
C Always prints five
D Sets x to 5 silently
Answer: B β SyntaxError - assignment is not allowed as a condition
A single = is assignment, and Python forbids it inside an if condition - you get a SyntaxError immediately. The comparison you want is == (two equals signs).
In C this bug compiles and runs wrong; Python catches it for you.
= vs ==SyntaxError
Q11.easy
How do you require BOTH conditions to be true?
if age >= 18 and has_id:
print("entry allowed")
A if a > 0 and b > 0:
B if a > 0 & also b > 0:
C if a > 0 && b > 0:
D if both(a > 0, b > 0):
Answer: A β if a > 0 and b > 0:
Python uses the English words: and, or, not - instead of &&, ||, !. 'if a > 0 and b > 0:' passes only when both are true.
Logical operators
Q13.easy
What does this print when fruit = "apple"?
if fruit in ["apple", "mango", "banana"]:
print("known fruit")
if fruit in ["apple", "mango", "banana"]: # clean
if fruit == "apple" or fruit == "mango" or fruit == "banana": # clumsy
A known fruit
B Nothing
C apple
D Error
Answer: A β known fruit
The in operator tests membership in a list - much cleaner than fruit == "apple" or fruit == "mango" or ... . "apple" is in the list, so it prints.
in operatorMembership
Q17.easy
What is the output of:
x = 3
if x > 10:
print("big")
A big
B Nothing at all
C False
D Error
Answer: B β Nothing at all
The condition is False and there's no else - so the block is skipped and the program simply continues. No output, no error.
if without else
Q20.easy
Can you put an if inside another if?
if logged_in:
if is_admin:
print("admin panel")
# often better:
if logged_in and is_admin:
print("admin panel")
A Yes - just indent one more level (nested if)
B No, Python forbids nesting
C Only with the nested keyword
D Only inside functions
Answer: A β Yes - just indent one more level (nested if)
Conditions nest freely - each level adds one more indent. But deep nesting gets hard to read; combining conditions with and is often cleaner.
Nestingand operator
Q25.easy
What is the output of:
age = "18"
if age == 18:
print("adult")
else:
print("hmm")
age = input("Age: ") # returns str!
if int(age) == 18: # convert first
print("adult")
A adult
B hmm
C 18
D Error
Answer: B β hmm
age is the STRING "18" (in quotes), and "18" == 18 is False - a string never equals a number in Python. This bug commonly appears with input(), which always returns strings.
input()Type conversionCommon gotchas
Q28.easy
if not is_raining: print("go outside")
When does this print?
if not logged_in:
print("please log in")
A When is_raining is True
B When is_raining is False
C Always
D Never
Answer: B β When is_raining is False
not flips the condition: 'if not is_raining' means 'if it is NOT raining'. When is_raining is False, not False is True, so it prints.
not operator
Medium questions (13)
Q5.medium
What is the output of:
x = 7
if x > 5:
print("A")
elif x > 6:
print("B")
# Order matters in elif chains!
# Put the most specific condition first.
A A
B B
C A then B
D Nothing
Answer: A β A
In an if/elif chain, Python stops at the FIRST True condition. x > 5 is True, so 'A' prints and the elif is never even checked - even though x > 6 is also True.
This is the key difference between elif and separate ifs.
elifEvaluation order
Q7.medium
What is the output of:
items = []
if items:
print("has items")
else:
print("empty")
if items: # Pythonic
if len(items) > 0: # works, but wordier
A has items
B empty
C []
D Error
Answer: B β empty
An empty list is falsy, so 'if items:' fails and else runs. This is the Pythonic way to test for emptiness - no need for len(items) == 0.
TruthinessEmpty collections
Q8.medium
What is the ternary (one-line) form of:
if age >= 18: status = "adult"
else: status = "minor"
status = "adult" if age >= 18 else "minor"
print("even" if n % 2 == 0 else "odd")
A status = "adult" if age >= 18 else "minor"
B status = if age >= 18 "adult" else "minor"
C status = age >= 18 ? "adult" : "minor"
D status = (age >= 18, "adult", "minor")
Answer: A β status = "adult" if age >= 18 else "minor"
Python's conditional expression reads like English: VALUE_IF_TRUE if CONDITION else VALUE_IF_FALSE. Option C is the C/Java/JS syntax, which Python doesn't use.
Ternary expressionConditional expression
Q12.medium
Which condition checks that x is between 10 and 20 (inclusive)?
x = 15
print(10 <= x <= 20) # True - preferred
print(x >= 10 and x <= 20) # True - also fine
A if 10 <= x <= 20:
B if x >= 10 and x <= 20:
C Both A and B work
D if x in (10, 20):
Answer: C β Both A and B work
Both are correct. Chained comparison (10 <= x <= 20) is the more Pythonic form. Option D only tests if x is EXACTLY 10 or 20, not in between.
Chained comparison
Q14.medium
What does the pass statement do?
if x > 5:
pass # TODO: handle this later
else:
print("small")
A Skips to the next loop iteration
B Nothing - it's a placeholder where code is syntactically required
C Exits the program
D Passes a value to a function
Answer: B β Nothing - it's a placeholder where code is syntactically required
pass does literally nothing. It exists because Python blocks can't be empty - use it as a placeholder for code you'll write later. (continue is the one that skips loop iterations.)
continuePlaceholders
Q16.medium
What is the correct way to check if a variable is None?
result = find_user("ana")
if result is None:
print("not found")
if result is not None:
print("found")
A if x is None:
B if x == None:
C if x = None:
D if None in x:
Answer: A β if x is None:
The convention (and PEP 8 rule) is 'is None' - identity check against the single None object. == None usually works but can be fooled by objects that override ==, and it's considered bad style.
Noneis operatorPEP 8
Q18.medium
What is the output of:
print(5 > 3)
is_adult = age >= 18 # store the bool
print(score > pass_mark) # print it directly
return n % 2 == 0 # return it from a function
A True
B yes
C 1
D 5
Answer: A β True
A comparison is an expression that evaluates to a bool - you can print it, store it, or return it directly. No if needed!
Writing 'if x > 5: return True else: return False' can be shortened to 'return x > 5'.
BooleansExpressions
Q19.medium
Grade logic: score = 95. What does this print?
if score >= 60:
print("C")
elif score >= 75:
print("B")
elif score >= 90:
print("A")
# Correct order - most specific first:
if score >= 90: print("A")
elif score >= 75: print("B")
elif score >= 60: print("C")
A A
B B
C C
D Nothing
Answer: C β C
The chain stops at the FIRST true condition: 95 >= 60 is True, so it prints 'C' - clearly not intended! In elif chains, always test the most restrictive condition FIRST (>= 90, then >= 75, then >= 60).
Classic interview trap about elif ordering.
elif orderingLogic bugs
Q21.medium
What is the output of:
name = ""
print("Hello, " + (name or "Guest"))
username = input("Name: ").strip()
print("Hello,", username or "Guest")
A Hello,
B Hello, Guest
C Hello, False
D Error
Answer: B β Hello, Guest
name is an empty string (falsy), so (name or "Guest") evaluates to "Guest" - or returns the first truthy operand. A neat idiom for default values.
Short-circuit orDefault values
Q24.medium
Python 3.10 added a switch-like statement. What is it called?
match command:
case "start":
print("starting")
case "stop":
print("stopping")
case _:
print("unknown")
A switch/case
B match/case
C select/when
D choose/option
Answer: B β match/case
match/case (structural pattern matching) arrived in Python 3.10. It compares a value against several patterns - like switch in other languages but more powerful. The underscore case is the default.
match statementPython 3.10
Q26.medium
Which is the correct one-line form (allowed but use sparingly)?
A if x > 5: print("big")
B if x > 5 then print("big")
C if x > 5 -> print("big")
D x > 5: print("big")
Answer: A β if x > 5: print("big")
A short body may sit on the same line after the colon: if x > 5: print("big"). Fine for tiny cases, but multi-line style is more readable and preferred by PEP 8.
Style (PEP 8)
Q27.medium
What is the output of:
x = 10
result = x if x > 100 else -x
print(result)
A 10
B -10
C 100
D Error
Answer: B β -10
The ternary picks the else-side because 10 > 100 is False: result = -x = -10. Read it as: 'result is x if x is big, otherwise negative x'.
Ternary expression
Q30.medium
A shop gives 10% discount to members AND seniors get 20% regardless of membership. Which order of checks is correct for a senior member to get 20%?
if is_senior:
discount = 20 # priority rule first
elif is_member:
discount = 10
else:
discount = 0
A Check is_senior first, then is_member in an elif
B Check is_member first, then is_senior in an elif
C Order doesn't matter with elif
D Use two separate if statements to apply both
Answer: A β Check is_senior first, then is_member in an elif
elif chains stop at the first match. If is_member is checked first, a senior member matches it and gets only 10%. Put the higher-priority rule (senior, 20%) first.
elif orderingBusiness logic
Hard questions (4)
Q15.hard
Bug hunt! Why does this print 'teen' for EVERY age?
if age == 13 or 14 or 15:
print("teen")
# WRONG - always True:
if age == 13 or 14 or 15:
# RIGHT:
if age in (13, 14, 15):
if age == 13 or age == 14 or age == 15:
A It's correct code
B or has higher precedence than ==
C 14 and 15 are evaluated as standalone truthy values, so the condition is always True
D == can't be used with or
Answer: C β 14 and 15 are evaluated as standalone truthy values, so the condition is always True
The condition parses as (age == 13) or (14) or (15). The bare numbers 14 and 15 are truthy on their own, so the whole condition is ALWAYS True. Correct: age in (13, 14, 15) or repeat the comparison.
One of the most common logic bugs in beginner Python code.
Truthinessin operatorCommon gotchas
Q22.hard
Why is the ORDER of this condition important?
if x != 0 and 10 / x > 2:
x = 0
if x != 0 and 10 / x > 2: # safe
...
# if 10 / x > 2 and x != 0: # crashes when x == 0!
A It isn't - order never matters with and
B and evaluates left to right and STOPS at the first False, so 10/x never runs when x is 0 - preventing ZeroDivisionError
C Python evaluates the right side first
D x != 0 is slower so it should be last
Answer: B β and evaluates left to right and STOPS at the first False, so 10/x never runs when x is 0 - preventing ZeroDivisionError
Short-circuiting: if x != 0 is False, Python skips the right side entirely. Reversed (10 / x > 2 and x != 0), a zero x would crash with ZeroDivisionError before the guard is reached.
Use the same trick with None: if obj is not None and obj.value > 5
Short-circuit evaluationGuard conditions
Q23.hard
not (a and b) is always equal to:
a, b = True, False
print(not (a and b)) # True
print(not a or not b) # True - same
A not a and not b
B not a or not b
C a or b
D not a and b
Answer: B β not a or not b
De Morgan's law: negating an AND turns it into an OR of negations. 'Not (rich and famous)' means 'not rich OR not famous'. Similarly, not (a or b) == not a and not b.
De Morgan's lawsBoolean logic
Q29.hard
What is the output of:
print(bool([]) == bool(""))
Both an empty list and an empty string are falsy: bool([]) is False and bool("") is False, and False == False is True. All empty containers share the same truthiness.