[Tutor] assert() question

Alan Gauld alan.gauld at btinternet.com
Sun Jul 6 10:23:54 CEST 2008


"Dick Moores" <rdm at rcblue.com> wrote

> I've heard about using assert() to check up 


> The top three work silently, but I found that I could not figure 
> out how to use assert() with the functions that print rather than 
> return. E.g., maxDiffBetPrimes() and printTime(). Is there a way?

Thats another good reason for not printing inside functions. 
Just get them to return the pre formatteed string which can 
be printed outside the function.

Unless you have a value to check you can't really use assert()
So if the function uses globals (which it shouldn't!) you might 
check them otherwise you are stuck.

> If it'll help, here's printTime():
> def printTime(timeEnd, timeStart):
>    from mycalc import hmsToText
>    timeElapsed = timeEnd - timeStart
>    if timeElapsed > 60:
>        print "Time was", hmsToText(timeElapsed)
>    else:
>        print "Time was %.4g seconds" % timeElapsed

Replace the prints with returns
change the function name to getTime()
Then call it with

t =  getTime(...)
print t

Now you can use an assert on t...

Of course if getTime is not your functin then 
modification may not be possible!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list