0

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

Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

1

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Your except clause asks for input from the user. But the second input is not tested. So when the second input is used in the float function, it will fail if the input is incorrect.

If you want the user to keep giving input until he inputs a number, you will need a loop. And within that loop, you will need a try-except clause (or some other test) to test wether the input was numerical.

Peter Pesch
  • 643
  • 5
  • 14