Python - Assertions
In Python programming, it is important to ensure that your code behaves as expected during development. Sometimes you want to check whether a condition is true at a specific point in your program. If the condition is false, the program should immediately stop and show an error.
For this purpose, Python provides a feature called Assertions.
Assertions are mainly used for debugging and testing. They help developers catch bugs early by validating assumptions in the code.
What is an Assertion in Python?
An assertion is a statement that checks whether a condition is true.
If the condition is:
- ✅ True → program continues normally
- ❌ False → program raises an
AssertionError
Syntax of Assertion
assert condition, "error message"condition→ expression that should be true"error message"→ optional message shown when assertion fails
Simple Example of Assertion
x = 10
assert x > 0, "x must be positive"
print("Value of x:", x)Output
Value of x: 10Since x > 0 is true, the program continues normally.
Example of Assertion Failure
x = -5
assert x > 0, "x must be positive"Output
AssertionError: x must be positiveThe program stops because the condition is false.
Why Use Assertions?
Assertions are useful for:
- Debugging code
- Checking assumptions
- Validating function inputs
- Detecting logical errors early
- Testing development code
Assertion in Functions
def square_root(x):
assert x >= 0, "Cannot calculate square root of negative number"
return x ** 0.5
print(square_root(16))Output
4.0If a negative value is passed:
print(square_root(-4))Output
AssertionError: Cannot calculate square root of negative numberMultiple Assertions Example
age = 20
balance = 1000
assert age >= 18, "User must be adult"
assert balance > 0, "Balance must be positive"
print("All conditions passed")Assertion in Data Validation
username = "admin"
password = "12345"
assert len(username) > 0, "Username cannot be empty"
assert len(password) >= 6, "Password too short"
print("User data is valid")Using Assertions for Debugging
def divide(a, b):
assert b != 0, "Denominator cannot be zero"
return a / b
print(divide(10, 2))Output
5.0Assertion with Lists
numbers = [1, 2, 3, 4]
assert len(numbers) > 0, "List is empty"
print(numbers)What is AssertionError?
When an assertion fails, Python raises:
AssertionErrorYou can also provide a custom message:
assert False, "Something went wrong"Disabling Assertions in Python
Assertions can be disabled when running Python in optimized mode:
python -O script.pyWhen disabled:
- All
assertstatements are ignored - No checks are performed
⚠️ Important: Never use assertions for critical logic.
Difference Between Assertion and Exception
| Feature | Assertion | Exception |
|---|---|---|
| Purpose | Debugging | Error handling |
| Used in production | ❌ Not recommended | ✅ Yes |
| Can be disabled | Yes | No |
| Raises | AssertionError | Various errors |
When to Use Assertions
Use assertions for:
- Internal checks
- Debugging conditions
- Development testing
- Validating assumptions
When NOT to Use Assertions
Avoid assertions for:
- User input validation
- Production error handling
- Business logic validation
Instead use try-except for those cases.
Example: Bad Use of Assertion
age = input("Enter age: ")
assert age.isdigit(), "Invalid age"⚠️ Problem:
- User input should use proper validation, not assertions.
Correct Approach
age = input("Enter age: ")
if not age.isdigit():
print("Invalid age")
else:
print("Valid age")Best Practices
1. Use Assertions for Debugging Only
assert x > 02. Always Add Clear Messages
assert balance > 0, "Balance must be positive"3. Do Not Use for Input Validation
Use proper error handling instead.
4. Keep Assertions Simple
Avoid complex logic inside assertions.
Real-World Applications
Assertions are commonly used in:
- Unit testing
- Software debugging
- Development environments
- Algorithm validation
- Data structure checks
- AI/ML model debugging
Summary
Assertions in Python are a debugging tool used to verify assumptions in code. They help detect errors early during development by checking whether a condition is true.
Key Takeaways
assertchecks conditions in Python- If condition is false → raises AssertionError
- Mainly used for debugging and testing
- Not recommended for production error handling
- Can be disabled using
-Oflag - Helps improve code reliability during development
Mastering assertions will help you write cleaner, safer, and more reliable Python code during the development phase.


0 Comments