7. Formatting the Time

Screen Link:

My Code:

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

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

hour_3 = 16
minute_3 = 9 
# answer to this input: 16:09
def format_time(hour,minute):
    if len(str(hour))==1:
        return("0"+str(hour)+':'+str(minute))
    if len(str(minute))==1:
        return(str(hour)+':'+"0"+str(minute))
    if len(str(minute))==1 and len(str(hour))==1:
        return("0"+str(hour)+':'+"0"+str(minute))
    else:
        return(str(hour)+':'+str(minute))
        
print(format_time(hour_2, minute_2))


What I expected to happen:

05:07

What actually happened:

05:7

How come it’s not adding a leading zero in front of the 7 str?

EDIT:
I’ve switched the order of the if statements below & got my solution correct. Anyone know why the above wasn’t working?

def format_time(hour,minute):
    if len(str(hour))==1 and len(str(minute))==1:
        return("0"+str(hour)+':'+"0"+str(minute))
    if len(str(hour))==1:
        return("0"+str(hour)+':'+str(minute))
    if len(str(minute))==1:
        return(str(hour)+':'+"0"+str(minute))
    else:
        return(str(hour)+':'+str(minute))
        
print(format_time(hour_2, minute_2))
1 Like

Hi @TravisBob

If you look at the order of execution of if statement and the input you are giving, you will understand what went wrong.

In your first case, the first if that gets executed is this

if len(str(hour))==1:
        return("0"+str(hour)+':'+str(minute))

Now you give hour =5, minute = 7

So what will happen?
len(5)=1 and the next line gets executed and it takes whatever input you have given and end up giving 05:7

In your second case

if len(str(minute))==1 and len(str(hour))==1:
        return("0"+str(hour)+':'+"0"+str(minute))

this is the first if clause and the next line gets executed only when both inputs are one digits, unlike in the previous case.

I hope this clarifies your doubt.