0% found this document useful (0 votes)
14 views3 pages

Assertions in Python

Assertions in Python are debugging aids that check conditions in code, raising an AssertionError if the condition is false. They are primarily used during testing to ensure internal correctness and catch errors early. Assertions can be disabled in optimized mode and should not replace proper error handling.

Uploaded by

pappumohana457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

Assertions in Python

Assertions in Python are debugging aids that check conditions in code, raising an AssertionError if the condition is false. They are primarily used during testing to ensure internal correctness and catch errors early. Assertions can be disabled in optimized mode and should not replace proper error handling.

Uploaded by

pappumohana457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Assertions in Python

Introduction to Assertions
Assertions are a debugging aid in Python. They are used to check whether a certain
condition in the code returns true. If the condition is false, the program will raise an
AssertionError with an optional error message.

Assertions are mainly used in testing and debugging phases to catch unexpected conditions
early in the development cycle.

Syntax of Assert
assert condition, message

- condition – a boolean expression that should be True during normal execution.


- message (optional) – the message to be displayed if the assertion fails.

Purpose of Assertions
- To ensure internal correctness of the program.
- To prevent bugs by catching errors early.
- To serve as documentation for assumptions made in the code.

How Assertion Works


- If the condition is true -> program continues.
- If the condition is false -> AssertionError is raised.

Example 1 – Positive Number Check


num = -10
assert num > 0, "Number must be positive"
print("Number is positive")

Output:
AssertionError: Number must be positive

Example 2 – List Length Check


def average(lst):
assert len(lst) > 0, "List must not be empty"
return sum(lst) / len(lst)

print(average([10, 20, 30])) # Works fine


print(average([])) # Raises AssertionError

Output:
20.0
AssertionError: List must not be empty

Use Case Scenarios


- Validate input types: assert isinstance(x, int), "Input must be an integer"
- Check list non-empty before access: assert len(my_list) > 0, "List is empty"
- Ensure value within expected range: assert 0 <= marks <= 100, "Invalid mark value"

Disabling Assertions
When Python is run in optimized mode using the -O flag, all assert statements are removed.
Command:
python -O program.py

Difference Between assert and Exception Handling


assert:
- Usage: Debugging/testing
- Behavior: Terminates with AssertionError
- Runtime Removal: Removed in optimized mode

try-except:
- Usage: Handling expected run-time errors
- Behavior: Handles exceptions gracefully
- Runtime Removal: Remains in code

Best Practices for Assertions


- Use assertions for internal self-checks, not for handling user input.
- Do not use them to replace error handling logic.
- Avoid side effects in assert conditions.

Conclusion
Assertions are a powerful tool in Python for verifying the correctness of code during
development and testing. They help catch logical errors early and improve the reliability of
software. However, they should be used carefully and not as a replacement for proper
exception handling.

You might also like