Sunday, February 12, 2017

Assertions

An assertion is a sanity-check that you can turn on or turn off when you have finish testing the program. An expression is tested, and if the result comes up false, an exception is raised. Assertion are carried out through use of assert statement.
print 1
assert 2 + 2 == 4
print 2
assert 1 + 1 == 3
print 3
1
2
AssertionError

Good practice is to place assertions at the start of a function to check for valid input and after a function call to check for valid output.
Example: what is the highest number printed by this code ?
print 0
assert 'h' != 'w'
print 1
assert False
print 2
assert True
print 3
0
1
AssertionError

Assertion can take a second argument that is passed to the AssertionError raised if the assertion fails. AssertionError expectations can be caught and handled like another exception using the try-except statement, but if not handled, this type of exception will terminate the program.
a = - 10
assert(a >= 0), 'Colder than absolute zero'
AssertionError: Colder than absolute zero

Example: Fill in the blanks to define function that takes one argument. Assert the argument to be positive.
___ function1(x):
    _____ x > 0, 'Error!'
    _____ x

userinput = _________ ("Enter a value: ")
val = int(_________)
print function1(______)   
First run:
Enter a value: -10
AssertionError: Error!

Second run:
Enter a value: 10
10
None


No comments:

Post a Comment