"Dick Moores" <[EMAIL PROTECTED]> 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.
Alan,
Actually, because of advice I've received here from mainly you, I now write very few functions for that module that print. But some, such as printTime(), are so handy to keep as is, that I hadn't rewritten them.
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!
I took your advice and now I have:
def get_time(timeEnd, timeStart):
from mycalc import hmsToText
timeElapsed = timeEnd - timeStart
if timeElapsed > 60:
return "Time was", hmsToText(timeElapsed)
else:
return "Time was %.4g seconds" % timeElapsed
And an assert() of
assert(get_time(1215322947.0320001, 1215312921.0054233) == ('Time was', '2 hours, 47 minutes, 6 seconds'))
But I have another assert() problem:
Another function of mine, fact(), has nary a print statement. But please take a look at it: < http://py77.python.pastebin.com/f157e2228>
I've repeated lines that follow fact() here:
if __name__ == '__main__':
"""
OUTPUT
6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000
1.925517662e+3423
3.629e+6
3628800
Traceback (most recent call last):
File "E:\PythonWork\Untitled 2.py", line 42, in <module>
assert(fact(10,4) == 3.629e+6)
AssertionError
"""
I trust the lines below the blank line in the output demonstrate the problem.
Is there a solution?
Dick
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
