1"""Quick note!
2This code snippet has been copied by Pseudo Balls.
3This is the original answer.
4Please consider justice by ignoring his answer.
5"""
6"""assert:
7evaluates an expression and raises AssertionError
8if expression returns False
9"""
10assert 1 == 1 # does not raise an error
11assert False # raises AssertionError
12# gives an error with a message as provided in the second argument
13assert 1 + 1 == 3, "1 + 1 does not equal 3"
14"""When line 7 is run:
15AssertionError: 1 + 1 does not equal 3
16"""
1assert <condition>,<error message>
2#The assert condition must always be True, else it will stop execution and return the error message in the second argument
3assert 1==2 , "Not True" #returns 'Not True' as Assertion Error.
1x = "hello"
2
3#if condition returns False, AssertionError is raised:
4assert x == "goodbye", "x should be 'hello'"
5-----------------------------------------------------------------
6Traceback (most recent call last):
7 File "demo_ref_keyword_assert2.py", line 4, in <module>
8 assert x == "goodbye", "x should be 'hello'"
9AssertionError: x should be 'hello'
1name = 'quaid'
2# check if name assigned is what assert expects else raise exception
3assert(name == 'sam'), f'name is {name}, it should be sam'
4
5print("Hello {check_name}".format(check_name = name))
6#output: Assertion Error
7# quaid is not what assert expects rather it expects sam as a string assigned to name variable
8# No print out is received
1def input_age(age):
2 try:
3 assert int(age) > 18
4 except ValueError:
5 return 'ValueError: Cannot convert into int'
6 else:
7 return 'Age is saved successfully'
8
9print(input_age('23')) # This will print
10print(input_age(25)) # This will print
11print(input_age('nothing')) # This will raise ValueError which is handled
12print(input_age('18')) # This will raise AssertionError, program collapses
13print(input_age(43)) # This won't print
1# Simple asserting thing, run it by using pytest or something
2# If you don't know how to run pytest, then go learn it.
3
4def test_math():
5 assert(1 + 1 == 2)
6
7# Another way to test it (without pytest) is:
8# You could just run the function to see if it makes an error.
9# If it doesn't, it means it was fine, if it does, it means there's an error.
10
11# But then again, using pytest or something is much easier and saves time.
12# So try to use testing applications instead of running the function to see.