Home » Python

assert keyword with example in Python

Python assert keyword: Here, we are going to learn about the assert keyword with example.
Submitted by IncludeHelp, on April 14, 2019

Python assert keyword

assert is a keyword (case-sensitive) in python, it is used to debug the code. Generally, it can be used to test a condition – if a condition returns False – it returns an Assertion Error (AssertionError).

Syntax of assert keyword

    assert statement

Example:

    Input:
    num = 10

    # assert statement
    assert num==20

    Output:
    assert num==20
    AssertionError

Python examples of assert keyword

Example 1: Test a False result

# python code to demonstrate example of 
# assert statement 

num = 10    # number

# assert statements

# nothing will happed as the condition is true
assert num==10

#AssertionError will generate as the condition is false
assert num==20

Output

Traceback (most recent call last):
  File "/home/main.py", line 12, in <module>
    assert num==20
AssertionError

Example 2: Test a False result and return a customize message

# python code to demonstrate example of 
# assert statement 

num = 10    # number

# assert statements

# nothing will happed as the condition is true
assert num==10

#AssertionError will generate as the condition is false
assert num==20, "There is an error with num's value"

Output

Traceback (most recent call last):
  File "/home/main.py", line 12, in <module>
    assert num==20, "There is an error with num's value"
AssertionError: There is an error with num's value



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.