assert function in python code example
Example 1: python assert
"""Quick note!
This code snippet has been copied by Pseudo Balls.
This is the original answer.
Please consider justice by ignoring his answer.
"""
"""assert:
evaluates an expression and raises AssertionError
if expression returns False
"""
assert 1 == 1
assert False
assert 1 + 1 == 3, "1 + 1 does not equal 3"
"""When line 7 is run:
AssertionError: 1 + 1 does not equal 3
"""
Example 2: assert syntax python
assert <condition>,<error message>
assert 1==2 , "Not True"
Example 3: assert keyword in python
The assert keyword is used when debugging code.
The assert keyword lets you test if a condition in your code returns
True, if not, the program will raise an AssertionError.
You can write a message to be written if the code returns False, check
the example below.
x = "hello"
assert x == "goodbye", "x should be 'hello'"
Example 4: how to use assert in python
assert type(num) is int,"num must be an integer"
Example 5: python assert
def input_age(age):
try:
assert int(age) > 18
except ValueError:
return 'ValueError: Cannot convert into int'
else:
return 'Age is saved successfully'
print(input_age('23'))
print(input_age(25))
print(input_age('nothing'))
print(input_age('18'))
print(input_age(43))