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.
1The assert keyword is used when debugging code.
2
3The assert keyword lets you test if a condition in your code returns
4True, if not, the program will raise an AssertionError.
5
6You can write a message to be written if the code returns False, check
7the example below.
8
9x = "hello"
10
11#if condition returns False, AssertionError is raised:
12assert x == "goodbye", "x should be 'hello'"
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