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

Screen Link:

https://app.dataquest.io/m/1012/python-fundamentals-practice-problems/7/formatting-the-time
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:

Output
10:30

05:07

16:09

What actually happened:

Output
10:30


5:07


16:09

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