[Tutor] assert - was: Calculating a math formula
Michael Janssen
Janssen@rz.uni-frankfurt.de
Tue Jan 14 11:42:15 2003
On Tue, 14 Jan 2003, Jens Kubieziel wrote:
> On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote:
> > def factorial(z):
> > assert z >= 0, "Invalid input: z must be nonnegative."
> ^^^^^^
> Where can I find some information what this exactly does? I searched my
> docs and find something on $PYTHONDOC/ref/assert.html. Are there some
> other examples?
another bit is in lib/module-exceptions.html#l2h-233:
exception AssertionError
Raised when an assert statement fails.
assert tests if expression is true and raise "AssertionError" if not.
In "long form":
if not z >= 0:
raise AssertionError, "Invalid input: z must be nonnegative."
Why to use this? As ref/assert.html states:
"Assert statements are a convenient way to insert debugging assertions
into a program" - it's shorter and more meaningful than an if-raise
statement.
Michael
>
> Now this function _always_ raises an exception. And I'm a bit perplex ...
sure? not on my system:
>>> def factorial(z):
... assert z >= 0, "Invalid input: z must be nonnegative."
... if z == 1 or z == 0:
... return 1
... else:
... return z*factorial(z-1)
...
>>> for n in range(5,-2,-1):
... print n, ":", factorial(n)
...
5 : 120
4 : 24
3 : 6
2 : 2
1 : 1
0 : 1
-1 :
> --
> Jens Kubieziel mailto:jens@kubieziel.de
> So, how's your love life? Still holding your own?
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>