πŸŽ“ Velnov

🐍 Python · Topic 5 of 20

Conditionals β€” Python Questions with Answers

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.

score = 82
if score >= 90:
    print("A")
elif score >= 75:
    print("B")
elif score >= 60:
    print("C")
else:
    print("Fail")
OutputB

2. Order matters in elif chains

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

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

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

MisconceptionCorrect 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

  1. When does an else block run?

    Show answer

    When none of the if/elif conditions were true.

  2. score = 95, and the chain checks >= 60 first. Which branch runs?

    Show answer

    The >= 60 branch, because it is the first true condition.

  3. What does if []: count as?

    Show answer

    False, because an empty list is falsy.

  4. Write a one-line condition that sets status to "adult" or "minor".

    Show answer

    status = "adult" if age >= 18 else "minor"

  5. Why is if age == 13 or 14: always true?

    Show answer

    14 alone is truthy, so the or is always true.

  6. How do you check if x is None?

    Show answer

    if x is None:

  7. What does pass do?

    Show answer

    Nothing; it is a placeholder.

  8. 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

Jump to: Easy Β· Medium Β· Hard

Easy questions (13)

Q1. easy

Which is the correct syntax for an if statement?

x = 10
if x > 5:
    print("big")
  1. A if (x > 5) { print("big") }
  2. B if x > 5:\n print("big")
  3. C if x > 5 then print("big")
  4. D if x > 5 print("big")

Answer: B β€” if x > 5:\n print("big")

Python's if needs a colon at the end of the condition and an INDENTED body on the next line. No parentheses or braces are required.

  • Forgetting the colon is the #1 beginner syntax error.

IndentationColon

Q2. easy

What does elif mean?

if score >= 90:
    print("A")
elif score >= 75:
    print("B")
elif score >= 60:
    print("C")
else:
    print("Fail")
  1. A End the if statement
  2. B 'Else if' - test another condition when the previous ones were False
  3. C A loop keyword
  4. 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
  1. A Always
  2. B Only when the if (and every elif) condition was False
  3. C Only when the if condition was True
  4. 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")

  1. A A
  2. B B
  3. C A then B
  4. 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
  1. A yes
  2. B no
  3. C 0
  4. 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")
  1. A n % 2 == 0
  2. B n / 2 == 0
  3. C n % 2 == 1
  4. 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")
  1. A Prints five when x is 5
  2. B SyntaxError - assignment is not allowed as a condition
  3. C Always prints five
  4. 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")
  1. A if a > 0 and b > 0:
  2. B if a > 0 & also b > 0:
  3. C if a > 0 && b > 0:
  4. 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
  1. A known fruit
  2. B Nothing
  3. C apple
  4. 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")

  1. A big
  2. B Nothing at all
  3. C False
  4. 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")
  1. A Yes - just indent one more level (nested if)
  2. B No, Python forbids nesting
  3. C Only with the nested keyword
  4. 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")
  1. A adult
  2. B hmm
  3. C 18
  4. 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")
  1. A When is_raining is True
  2. B When is_raining is False
  3. C Always
  4. 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.
  1. A A
  2. B B
  3. C A then B
  4. 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
  1. A has items
  2. B empty
  3. C []
  4. 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")
  1. A status = "adult" if age >= 18 else "minor"
  2. B status = if age >= 18 "adult" else "minor"
  3. C status = age >= 18 ? "adult" : "minor"
  4. 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
  1. A if 10 <= x <= 20:
  2. B if x >= 10 and x <= 20:
  3. C Both A and B work
  4. 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")
  1. A Skips to the next loop iteration
  2. B Nothing - it's a placeholder where code is syntactically required
  3. C Exits the program
  4. 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")
  1. A if x is None:
  2. B if x == None:
  3. C if x = None:
  4. 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
  1. A True
  2. B yes
  3. C 1
  4. 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")
  1. A A
  2. B B
  3. C C
  4. 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")
  1. A Hello,
  2. B Hello, Guest
  3. C Hello, False
  4. 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")
  1. A switch/case
  2. B match/case
  3. C select/when
  4. 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)?

  1. A if x > 5: print("big")
  2. B if x > 5 then print("big")
  3. C if x > 5 -> print("big")
  4. 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)

  1. A 10
  2. B -10
  3. C 100
  4. 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
  1. A Check is_senior first, then is_member in an elif
  2. B Check is_member first, then is_senior in an elif
  3. C Order doesn't matter with elif
  4. 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:
  1. A It's correct code
  2. B or has higher precedence than ==
  3. C 14 and 15 are evaluated as standalone truthy values, so the condition is always True
  4. 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!
  1. A It isn't - order never matters with and
  2. B and evaluates left to right and STOPS at the first False, so 10/x never runs when x is 0 - preventing ZeroDivisionError
  3. C Python evaluates the right side first
  4. 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
  1. A not a and not b
  2. B not a or not b
  3. C a or b
  4. 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(""))

print(bool([]))    # False
print(bool(""))    # False
print(bool({}))    # False
print(bool(0))     # False
  1. A True
  2. B False
  3. C Error
  4. D None

Answer: A β€” True

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.

TruthinessFalsy values

Practice β€œConditionals” as a quiz