python assert exception code example

Example 1: python assert statement

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

Example 2: assert syntax python

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.

Example 3: assert python 3

# 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.

Example 4: how to use assert in python

assert type(num) is int,"num must be an integer"