Issue
I’m trying to pass test case 1 but I’m getting an extra ‘None’ and ‘F’ line in the output. I’m not sure where it’s coming from? Hence my test case fails even though the correct new time prints on the next line.
python main.py
1:08 AM
None
5:42 PM
F
======================================================================
FAIL: test_same_period (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/runner/boilerplate-time-calculator/test_module.py", line 10, in test_same_period
self.assertEqual(actual, expected, 'Expected calling "add_time()" with "3:30 PM", "2:12" to return "5:42 PM"')
AssertionError: None != '5:42 PM' : Expected calling "add_time()" with "3:30 PM", "2:12" to return "5:42 PM"
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Take a closer look at lines 27 and 29 in your code. Remember that print function prints out the text, but it returns None. So after those lines are executed the value returned by your function is actually None.
Ah. Thanks! I removed the print function and it runs now. I could also use return.
I have another question. Why does the print function not behave that way in this scenario where I’m calling the add_time function within my time_calculator.py file (no main or test module)?
def add_time(start, duration):
hour, min = map(int, start[:-2].split(':')) # removes AM/PM characters
dhour, dmin = map(int, duration.split(':'))
# modulo operate the hour by 12 to work with integers 0-11 on a 12-hour clock
hour %= 12
dhour %= 12
if start[-2:] == 'PM':
hour += 12
duration = (dhour * 60) + dmin
time = (hour * 60) + min + duration
hour, min = divmod(time, 60)
# if hour value > 24 we need the reminder to return to 0-11 integers
hour %= 24
period = 'A' if hour < 12 else 'P'
hour %= 12
if hour == 0:
hour = 12
if min < 10:
new_time = print("{}:0{} {}M".format(hour, min, period))
else:
new_time = print("{}:{} {}M".format(hour, min, period))
return new_time
add_time("11:06 PM", "2:02")
add_time("3:30 PM", "2:12")
PS C:\Coding\python-workspace> c:; cd 'c:\Coding\python-workspace'; & 'C:\Users\johan\AppData\Local\Programs\Python\Python39\python.exe' 'c:\Users\johan\.vscode\extensions\ms-python.python-2021.7.1060902895\pythonFiles\lib\python\debugpy\launcher' '52098' '--' 'c:\Coding\python-workspace\FCC-Python-Cert\time-calculator\time_calculator.py'
1:08 AM
5:42 PM
PS C:\Coding\python-workspace>
It behaves the same, but here function is used differently. In main.py function call is wrapped in anotherprint, making it print out what function returned - the None. Similarly test module compares the result returned by function.