Python Programming – Assert Statement

You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.

Python Programming – Assert Statement

The assert statement checks if a given logical expression is true; or false. The program executes only if the expression is true and otherwise it raises the AssertionError. The syntax of assert is:
assert Expression[, Arguments]

Example
Demo of an assert statement.

# Demo of the assert statement
num=int(input(‘Enter a number: ‘))
assert num>=0
print(‘You entered: nun)
RUN
>>>
Enter a number: 8 You entered: 8
>>>
>>>
Enter a number: -4
Traceback (most recent call last):
File “C:\Users\shash\AppData\Local\Programs\Python\Python37-32\assert.py”, line 2, in <module>
assert num>=0
AssertionError
>>>

The print statement will display if the entered number is greater than or equal to 0. Negative numbers result in aborting the program after showing the AssertionError as shown in Figure 5.56. So, Assertions are simply boolean expressions that check if the condition returns true or not. If it is true, the program does nothing and moves to the next line of code. However, if it’s false, the program stops and throws an error.

  • Python assert statement is a debugging aid that tests a condition, it brings the program to halt as soon as any error is occurred and shows the point of the program where an error has occurred.

The AssertionError is also a built-in exception and can be handled using the try…except construct. An expression is tested, and if the result comes up false, an exception is raised. For example,

try:
num=int(Input(‘Enter a number: ‘))
#if condition returns False, AssertionError Is raised:
assert(num >=0), “Only positive numbers accepted.”
print(num)
except AssertionError as msg:
print(msg)

Leave a Reply

Your email address will not be published. Required fields are marked *