[Tutor] about assert

Marc Poulin marc_a_poulin at yahoo.com
Wed Sep 13 15:47:25 CEST 2006


--- "linda.s" <samrobertsmith at gmail.com> wrote:

> Python manual has a very brief introduction of
> "assert" statements. It
> is very difficult for me to understand it.


Every program has some fundamental assumptions that
must remain true in order for the program to continue
giving correct results.

The assert statement is used to verify those
assumptions. (The optional 2nd parameter can be used
to give additional information about what went wrong.)

For example, in my world no one is allowed to have a
negative age. A negative age means my program is
hopelessly confused and should halt immediately.

>>> myAge=42
>>> assert myAge>=0  ## this is OK

>>> myAge= -1        ## logically impossible
>>> assert myAge >= 0
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AssertionError

## here I print the condition that failed
>>> assert myAge >=0, 'myAge >= 0'
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AssertionError: myAge >= 0


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Tutor mailing list