Converting time to hh:mm using a function, can't figure out what I'm doing wrong

Screen Link:
My Code:

# provided inputs
hour_1 = 10
minute_1 = 30 
# answer to this input: 10:30

def format_time(h,m):
    h = str(h)+':'
    if (len(h)) == 1:
        h = (h.zfill(2))
    m = str(m)
    if (len(m)) == 1:
        m = (m.zfill(2))
    return (h+m)

hm_1 = format_time(hour_1, minute_1)

hour_2 = 5
minute_2 = 7 
# answer to this input: 05:07

hm_2 = format_time(hour_2, minute_2)

hour_3 = 16
minute_3 = 9 
# answer to this input: 16:09

hm_3 = format_time(hour_3, minute_3)

print (hm_1)
print ('\n')
print (hm_2)
print ('\n')
print (hm_3)
print ('\n')

What I expected to happen:




What actually happened:




Can someone tell me what I’m doing wrong in my code? I am trying to pad each variable with a zero but for some reason only the second variable is getting padded and not the first.

It’s because of the following piece of code -

You first modify h so that it includes the :. At this point, the length of h changes.

If you had h as 5, now it’s 5:. So, your if condition will never be True as len(h) is 2.

You need to modify the code accordingly.

1 Like

Thank you! Didn’t even think about that!

1 Like