More on Assertions

Assertions are not just for debugging

Ensure a condition is True

#!/usr/bin/python3

from math import sqrt

def mySqrt(num):
    assert num >= 0

    return sqrt(num)

""" Tests """
if __name__ == "__main__":
    print (mySqrt(4))
    print (mySqrt(-4))

[Download assert1.py]

Test that what you expected to happen did happen...

#!/usr/bin/python3

filename = 'test2.dat'
file     = open(filename, 'r')

lines = []   # Initialize an empty list

for line in file:
    lines.append(line)

file.close()

assert len(lines) != 0

[Download assert2.py] [Data (test2.dat)]

Assertions as comments

#!/usr/bin/python3

filename = 'test3.dat'
file     = open(filename, 'r')

lines = []   # Initialize an empty list

for line in file:
    line = line.rstrip()     # Remove return character
    assert line[0:1] == '!'  # Check the file format
    line = line[1:]          # Remove first character
    lines.append(line)

file.close()

for line in lines:
    print(line)

[Download assert3.py] [Data (test3.dat)]

Continue