Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The assert Statement

An assertion is a condition that we're claiming should be true at this point in the program. Typically, it summarizes the state of the program's variables. Assertions can help explain the relationships among variables, review what has happened so far in the program, and show that if statements and for or while loops have the desired effect.

When a program is correct, all of the assertions are true no matter what inputs are provided. When a program has an error, at least one assertion winds up false for some combination of inputs.

Python directly supports assertions through an assert statement. There are two forms:

assert condition

assert condition 〉 〈 , expression

If the condition is False, the program is in error; this statement raises an AssertionError exception. If the condition is True, the program is correct, this statement does nothing more.

If the second form of the statement is used, and an expression is given, an exception is raised using the value of the expression. We'll cover exceptions in detail in Chapter 17, Exceptions . If the expression is a string, it becomes an the value associated with the AssertionError exception.

Note

There is an even more advanced feature of the assert statement. If the expression evaluates to a class, that class is used instead of AssertionError. This is not widely used, and depends on elements of the language we haven't covered yet.

Here's a typical example:

max= 0
if a < b: max= b
if b < a: max= a
assert (max == a or max == b) and max >= a and max >= b

If the assertion condition is true, the program continues. If the assertion condition is false, the program raises an AssertionError exception and stops, showing the line where the problem was found.

Run this program with a equal to b and not equal to zero; it will raise the AssertionError exception. Clearly, the if statements don't set max to the largest of a and b when a = b. There is a problem in the if statements, and the presence of the problem is revealed by the assertion.


 
 
  Published under the terms of the Open Publication License Design by Interspire