assert python 3
"""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
2
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')) # This will print
print(input_age(25)) # This will print
print(input_age('nothing')) # This will raise ValueError which is handled
print(input_age('18')) # This will raise AssertionError, program collapses
print(input_age(43)) # This won't print
Thank you!
2
0
4
5
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!
5
0
0
0
# Simple asserting thing, run it by using pytest or something
# If you don't know how to run pytest, then go learn it.
def test_math():
assert(1 + 1 == 2)
# Another way to test it (without pytest) is:
# You could just run the function to see if it makes an error.
# If it doesn't, it means it was fine, if it does, it means there's an error.
# But then again, using pytest or something is much easier and saves time.
# So try to use testing applications instead of running the function to see.
Thank you!
0
0
5
2
assert <condition>,<error message>
#The assert condition must always be True, else it will stop execution and return the error message in the second argument
assert 1==2 , "Not True" #returns 'Not True' as Assertion Error.
Thank you!
2
0
4
9
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!
9
0
Are there any code examples left?
New code examples in category Python