An assert statement helps check if something is true while your program runs. If it is not true, the program stops and shows an error. This helps find mistakes early.
Assert statement usage in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
assert condition, "error message"
The condition is what you expect to be true.
The error message is optional but helps explain the problem if the assertion fails.
Examples
x is greater than zero. If not, the program stops.Python
assert x > 0
Python
assert len(my_list) > 0, "List should not be empty"
name is a string type.Python
assert isinstance(name, str), "Name must be a string"
Sample Program
This program defines a function to divide two numbers. It uses assert to stop if the second number is zero, avoiding a crash later.
Python
def divide(a, b): assert b != 0, "Cannot divide by zero" return a / b print(divide(10, 2)) print(divide(5, 0))
Important Notes
Assertions are mainly for debugging and testing, not for handling user errors in production.
You can disable all assertions when running Python with the -O option.
Summary
Assert checks if something is true and stops the program if not.
It helps catch bugs early by verifying assumptions.
Use clear messages to explain what went wrong.
Practice
1. What does the
assert statement do in Python?easy
Solution
Step 1: Understand the purpose of assert
The assert statement tests a condition and raises an error if the condition is false.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.Final Answer:
Checks if a condition is true and stops the program if false -> Option DQuick 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
Solution
Step 1: Recall assert syntax
The correct syntax isassert condition, messagewith a comma separating condition and message.Step 2: Check each option
Only assert x > 0, "x must be positive" uses a comma correctly between condition and message.Final Answer:
assert x > 0, "x must be positive" -> Option AQuick 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
Solution
Step 1: Analyze first function call
check_age(20) passes the assert since 20 >= 18, so it returns "Access granted" and prints it.Step 2: Analyze second function call
check_age(16) fails the assert because 16 < 18, so it raises AssertionError with the message.Final Answer:
Access granted\nAssertionError: Age must be at least 18 -> Option BQuick 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
Solution
Step 1: Check assert syntax
Assert requires a comma between the condition and the message string.Step 2: Identify the error
The code misses the comma, causing a syntax error.Final Answer:
Missing comma between condition and message -> Option AQuick 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
Solution
Step 1: Understand assert in loop context
We want to check each number and stop if any is not positive, showing which one failed.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.Final Answer:
assert n > 0, f"Number {n} is not positive" -> Option CQuick 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
