assert keyword python
"""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 # does not raise an error
assert False # raises AssertionError
# gives an error with a message as provided in the second argument
assert 1 + 1 == 3, "1 + 1 does not equal 3"
"""When line 7 is run:
AssertionError: 1 + 1 does not equal 3
"""
4
6
x = "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye", "x should be 'hello'"
-----------------------------------------------------------------
Traceback (most recent call last):
File "demo_ref_keyword_assert2.py", line 4, in <module>
assert x == "goodbye", "x should be 'hello'"
AssertionError: x should be 'hello'
Thank you!
6
0
4.5
2
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"
#if condition returns False, AssertionError is raised:
assert x == "goodbye", "x should be 'hello'"
Thank you!
2
0
5
1
name = 'quaid'
# check if name assigned is what assert expects else raise exception
assert(name == 'sam'), f'name is {name}, it should be sam'
print("Hello {check_name}".format(check_name = name))
#output: Assertion Error
# quaid is not what assert expects rather it expects sam as a string assigned to name variable
# No print out is received
Thank you!
1
0
Are there any code examples left?
New code examples in category Python