Skip to content
Advertisement

Python ValueError: could not convert string to float: ‘exit’

The below code works for integers, negative and decimal numbers. The issue is that Id like it to jump to the else statement below if someone types exit or if someone types any string to either exit the program or give an I dont understand message. Appreciate the help.

temp = ""

while temp != "exit":
    temp = float(input("Enter a temperature or type exit: "))
    #check if its number or else kick it to the else statement
    if type(temp) == float or temp.isnumeric() == True :
        unit = input("Enter unit('C' for Celsius or 'F' for Fahrenheit): ")
        if unit == 'C' or unit == 'c' :
            newTemp = int(round((9 * temp) / 5 + 32))
            print("The temperature in Fahrenheit is", newTemp)
        else:
            if unit == 'F' or unit == 'f' :
             newTemp = int(round((temp - 32) * 5 / 9))
             print("Temperature in Celsius =", newTemp)
    else:
        if temp.lower() == "exit":
            temp = temp.lower()
            print("Goodbye!")
        else:
            print("I dont understand. Try again.n")

Advertisement

Answer

Try this. It converts the input to string, then tries to convert it to float (both integers and floats can be converted to floats, hence it checks if it is numeric).
If it can’t be converted to float, then it is a string and stays that way for the if-else statements.

temp = ""

while temp != "exit":
    temp = str(input("Enter a temperature or type exit: "))
    try:
        temp=float(temp)
    except ValueError:
        pass
    #check if its number or else kick it to the else statement
    if type(temp) == float:
        unit = input("Enter unit('C' for Celsius or 'F' for Fahrenheit): ")
        if unit == 'C' or unit == 'c' :
            newTemp = int(round((9 * temp) / 5 + 32))
            print("The temperature in Fahrenheit is", newTemp)
        else:
            if unit == 'F' or unit == 'f' :
             newTemp = int(round((temp - 32) * 5 / 9))
             print("Temperature in Celsius =", newTemp)
    else:
        if temp.lower() == "exit":
            temp = temp.lower()
            print("Goodbye!")
        else:
            print("I dont understand. Try again.n")
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement