4.6: Sanity Checks with assert Statements
- Page ID
# Memory Puzzle # By Al Sweigart email@example.com # http://inventwithpython.com/pygame # Released under a "Simplified BSD" license import random, pygame, sys from pygame.locals import * FPS = 30 # frames per second, the general speed of the program WINDOWWIDTH = 640 # size of window's width in pixels WINDOWHEIGHT = 480 # size of windows' height in pixels REVEALSPEED = 8 # speed boxes' sliding reveals and covers BOXSIZE = 40 # size of box height & width in pixels GAPSIZE = 10 # size of gap between boxes in pixels BOARDWIDTH = 10 # number of columns of icons BOARDHEIGHT = 7 # number of rows of icons assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches.' XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2) YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)
assert statement on line 15 ensures that the board width and height we’ve selected will result in an even number of boxes (since we will have pairs of icons in this game). There are three parts to an
assert statement: the
assert keyword, an expression which, if
False, results in crashing the program. The third part (after the comma after the expression) is a string that appears if the program crashes because of the assertion.
assert statement with an expression basically says, "The programmer asserts that this expression must be
True, otherwise crash the program." This is a good way of adding a sanity check to your program to make sure that if the execution ever passes an assertion we can at least know that that code is working as expected.