Ticker

6/recent/ticker-posts

Assert Statement in Python

Assert Statement in Python

Definition:
The assert statement in Python is used to check if a given condition evaluates to True during program execution. If the condition is True, the program continues to execute as usual. However, if the condition is False, the assert statement raises an AssertionError and halts the program's execution.

Syntax:

python
assert condition, error_message

Explanation:

  • condition: This is the expression that is evaluated. If it is true, the program continues; otherwise, an AssertionError is raised.
  • error_message: This is an optional argument that can be used to provide a custom error message when the assertion fails. If omitted, a default error message is shown.

Usage:
The assert statement is commonly used during debugging and testing to check whether certain conditions are met at specific points in the code.

Example:
Let's say we want to create a function to calculate the factorial of a positive integer. We can use an assert statement to ensure that the input is positive.

python
def factorial(n):
assert n >= 0, "Input must be a non-negative integer"
result = 1
for i in range(1, n + 1):
result *= i
return result

In this example, if we call the factorial function with a negative integer or a non-integer value, the assert statement will raise an AssertionError with the specified error message.

Note:
It's essential to use assert statements only for debugging and testing purposes, as they can be disabled globally with the -O (optimize) command-line switch or the PYTHONOPTIMIZE environment variable. As a result, assert statements might not execute in optimized production code. Therefore, they should not be relied upon for regular error handling or input validation.

Post a Comment

0 Comments