Search code examples
pythoncs50

Why is the input still a string type after running it through a function to turn it into a float?


I type a time like 7:30 run it through the convert() function to turn that into a float that would equal 7.5. Then call it back to main() and check what type it is now, and it gives me it's still a str not a float.

def main():
    meal_time = input("What time is it?").strip()   
    convert(meal_time)
    print(type(meal_time))

def convert(time):
    hour, minu = time.split(":") 
    hour = float(hour) #7.0
    minu = float(minu) / 60 
    return float(hour+minu)

if __name__ == "__main__":
    main()

Input

7:30

Output

type 'str'

Solution

  • You're not updating meal_time in main() with the float returned from convert(). Functions in Python don't modify the original variable unless it's mutable and you're explicitly changing it.

    Instead of:

    convert(meal_time)
    

    Try:

    meal_time = convert(meal_time)
    

    Output you should observe after the above change:

    <class 'float'>