Bird
Raised Fist0
Pythonprogramming~10 mins

Assert statement usage in Python - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the variable age is at least 18 using an assert statement.

Python
age = 20
assert [1], "Age must be at least 18"
Drag options to blanks, or click blank then click option'
Aage > 18
Bage >= 18
Cage = 18
Dage < 18
Attempts:
3 left
💡 Hint
Common Mistakes
Using assignment (=) instead of comparison (>=).
Checking if age is less than 18 instead of greater or equal.
2fill in blank
medium

Complete the code to assert that the list numbers is not empty.

Python
numbers = [1, 2, 3]
assert [1], "List should not be empty"
Drag options to blanks, or click blank then click option'
Alen(numbers) == 0
Bnumbers is None
Cnumbers == []
Dlen(numbers) > 0
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if length equals zero instead of greater than zero.
Comparing the list directly to an empty list incorrectly.
3fill in blank
hard

Fix the error in the assert statement that checks if score is between 0 and 100 inclusive.

Python
score = 85
assert 0 <= score and score [1] 100, "Score must be between 0 and 100"
Drag options to blanks, or click blank then click option'
A<=
B==
C>
Dor
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'or' which allows invalid scores.
Using '==' which only checks equality, not range.
4fill in blank
hard

Fill both blanks to assert that the string name is not empty and has length less than 10.

Python
name = "Alice"
assert [1] and [2], "Name must be non-empty and shorter than 10 characters"
Drag options to blanks, or click blank then click option'
Alen(name) > 0
Blen(name) == 0
Clen(name) < 10
Dlen(name) > 10
Attempts:
3 left
💡 Hint
Common Mistakes
Using length equal to zero instead of greater than zero.
Checking length greater than 10 instead of less than 10.
5fill in blank
hard

Fill all three blanks to create a dictionary valid_scores with keys as uppercase names and values as scores greater than 50.

Python
scores = {"alice": 60, "bob": 45, "carol": 75}
valid_scores = { [1]: [2] for name, score in scores.items() if score [3] 50 }
Drag options to blanks, or click blank then click option'
Aname.upper()
Bscore
C>
Dname.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using name.lower() instead of upper().
Using score less than or equal to 50.
Swapping keys and values in the comprehension.

Practice

(1/5)
1. What does the assert statement do in Python?
easy
A. Prints a message when a condition is false
B. Runs a loop until a condition is true
C. Defines a function to check conditions
D. Checks if a condition is true and stops the program if false

Solution

  1. Step 1: Understand the purpose of assert

    The assert statement tests a condition and raises an error if the condition is false.
  2. Step 2: Compare options with assert behavior

    Only Checks if a condition is true and stops the program if false correctly describes assert's behavior of stopping the program when the condition is false.
  3. Final Answer:

    Checks if a condition is true and stops the program if false -> Option D
  4. Quick Check:

    Assert checks condition and stops if false [OK]
Hint: Assert stops program if condition is false [OK]
Common Mistakes:
  • Thinking assert runs loops
  • Confusing assert with print
  • Believing assert defines functions
2. Which of the following is the correct syntax for an assert statement with a message?
easy
A. assert x > 0, "x must be positive"
B. assert (x > 0) "x must be positive"
C. assert x > 0; "x must be positive"
D. assert x > 0: "x must be positive"

Solution

  1. Step 1: Recall assert syntax

    The correct syntax is assert condition, message with a comma separating condition and message.
  2. Step 2: Check each option

    Only assert x > 0, "x must be positive" uses a comma correctly between condition and message.
  3. Final Answer:

    assert x > 0, "x must be positive" -> Option A
  4. Quick Check:

    Assert syntax uses comma before message [OK]
Hint: Use comma between condition and message in assert [OK]
Common Mistakes:
  • Using colon or semicolon instead of comma
  • Missing comma before message
  • Putting message without quotes
3. What will be the output of this code?
def check_age(age):
    assert age >= 18, "Age must be at least 18"
    return "Access granted"

print(check_age(20))
print(check_age(16))
medium
A. Access granted\nAccess granted
B. Access granted\nAssertionError: Age must be at least 18
C. AssertionError: Age must be at least 18\nAccess granted
D. No output, program crashes immediately

Solution

  1. Step 1: Analyze first function call

    check_age(20) passes the assert since 20 >= 18, so it returns "Access granted" and prints it.
  2. Step 2: Analyze second function call

    check_age(16) fails the assert because 16 < 18, so it raises AssertionError with the message.
  3. Final Answer:

    Access granted\nAssertionError: Age must be at least 18 -> Option B
  4. Quick Check:

    Assert stops program on false condition with error [OK]
Hint: Assert stops at first false condition with error [OK]
Common Mistakes:
  • Thinking both print statements run
  • Ignoring the error message
  • Assuming assert prints message without error
4. Find the error in this code snippet:
assert x > 10 "x should be greater than 10"
medium
A. Missing comma between condition and message
B. Missing parentheses around condition
C. Message should be a variable, not a string
D. Assert cannot have a message

Solution

  1. Step 1: Check assert syntax

    Assert requires a comma between the condition and the message string.
  2. Step 2: Identify the error

    The code misses the comma, causing a syntax error.
  3. Final Answer:

    Missing comma between condition and message -> Option A
  4. Quick Check:

    Comma separates condition and message in assert [OK]
Hint: Always put a comma before the assert message [OK]
Common Mistakes:
  • Using colon or space instead of comma
  • Thinking parentheses are mandatory
  • Believing assert can't have messages
5. You want to check a list of numbers to ensure all are positive using assert. Which code correctly uses assert inside a loop to do this?
nums = [3, 5, -1, 7]
for n in nums:
    ?
hard
A. assert n > 0; f"Number {n} is not positive"
B. assert n > 0: f"Number {n} is not positive"
C. assert n > 0, f"Number {n} is not positive"
D. assert (n > 0), "Number n is not positive"

Solution

  1. Step 1: Understand assert in loop context

    We want to check each number and stop if any is not positive, showing which one failed.
  2. Step 2: Check syntax correctness

    assert n > 0, f"Number {n} is not positive" uses correct assert syntax with a comma and f-string for message. Others use invalid punctuation.
  3. Final Answer:

    assert n > 0, f"Number {n} is not positive" -> Option C
  4. Quick Check:

    Assert syntax: condition, message with comma [OK]
Hint: Use comma and f-string for assert message in loops [OK]
Common Mistakes:
  • Using colon or semicolon instead of comma
  • Not using f-string for variable message
  • Putting message outside assert statement