Search code examples
pythontry-catchuser-inputexceptvalueerror

Python: try, except ValueError only works once


I have an assignment to make a Fahrenheit to Clesius calculator and to use the try and except ValueError function but I can't enter a wrong value more than once or it crashes. I want the user to enter a number and not letters. This is how my code looks now

print("Hej och välkommen till Fahrenheit omvandlaren")
Fahrenheit = (input("Vänligen ange grader i Fahrenheit: "))

try:
    test = float(Fahrenheit)

except ValueError:
    Fahrenheit = (input("Vänligen ange ett tal!"))

Celsius = (float(Fahrenheit)-32)*5/9
print(Fahrenheit, "Fahernheit är lika med",(round(Celsius,2)),"grader Celsius")

I'm new to programming in general and would appreciate if you can explain in a simple way how to make it possible to enter strings multiple times without having the program crashing


Solution

  • You can could put the input in a loop:

    while True:
        fahrenheit = (input("Vänligen ange grader i Fahrenheit: "))
        try:
            test = float(fahrenheit)
            break
        except ValueError:
            pass