Im stuck with "None" output

In exercice about What time is it?:

I tried to print time in format Hour:Minute:Seconds.
The problem is I’m getting good output, but with additional " None" output.
I have no idea why this “None” is printed.

# provided inputs
num_seconds1 = 62589 
# answer to this input: 17, 23, 9

num_seconds2 = 10000 
# answer to this input: 2, 46, 40

def seconds_to_hour_minute(num_seconds):
    hour = num_seconds / 3600
    minute = (hour - int(hour)) * 60
    seconds = round(((num_seconds / 60) - int(num_seconds / 60)) * 60)
    
    if seconds < 10:
        time = print(int(hour), ":", int(minute), ":", 0, round(seconds), sep="")
    else:
        time = print(int(hour), ":", int(minute), ":", round(seconds), sep="")
        return time
    
print(seconds_to_hour_minute(num_seconds1))
print('\n')
print(seconds_to_hour_minute(num_seconds2))

image

This is because of how python internally works and can be tricky to figure out.

But the main reasons behind why you see this is -

  • You are saving print statements into a variable
  • You are returning time only from your else condition

When you do something like -

a = print("hi")

and run the above code, Python still prints out that hi. But a doesn’t technically store anything in it. It’s a NoneType.

So, if you were to do -

print(a)

and run the code. hi would still be printed, but after that you would see a None.

In your function, something similar happens. The print statement(s) get printed regardless. But time doesn’t store anything in it. It contains a None.

So, this leads to two situations -

1. When seconds < 10

In this case, you don’t have a return statement. So, what happens is the print statement gets printed. time has a None in it.

BUT, because that part of your code has no return statement in it AND you are trying to print the output of the function using -

print(seconds_to_hour_minute(num_seconds1))

It returns a None. Because the function is not returning anything for you to print.

2. When seconds >= 10

In this case, like before, the print statement gets printed out. time contains a None. You return time, and since you are printing out the output of this function call, the None also gets printed out.

Once you format your code appropriately, you should not see that None anymore.

1 Like