0

I am attempting to make a temperature converter using python. The goal is to have the user input the current temperature, convert it to float, then convert it. I pretty much have that part done. However, to make the code less brittle, I was attempting to figure out a way to stop the user from putting non-number values as their initial temperature. Could you help me figure this out? Also any other suggestions for error checking would be greatly appreciated.

#We will begin with asking the user for what the temperature they want to use and converts it to a float
temperature =float(input("Please enter the whole number value of the temperature. "))

#Next we will ask the user if they are using Fahrenheit and Celcius
unit = input("Is this celcius or fahrenheit? ")

#Checks to see if the unit used is  Celcius
if unit == "celcius"  or unit == "Celcius":
    celcius = temperature * 9/5 + 32.0
    print(celcius)
elif unit == "fahrenheit" or unit == "Fahrenheit":
    fahrenheit = (temperature - 32.0) * 5/9
    print(fahrenheit)
else:
    print("Invalid unit. Exiting program.")
Jibril Burleigh
  • 104
  • 1
  • 10
  • Probable duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/2823755) – wwii Mar 11 '15 at 04:46

2 Answers2

0

How about

while True:
    try:
        temperature = float(input("Please enter the whole number value of the temperature. "))
        break
    except ValueError:
        print('Invalid input')

Also,

if unit.lower() == "celcius":

is usually safer than

if unit == "celcius"  or unit == "Celcius":
Alex
  • 18,484
  • 8
  • 60
  • 80
0
#We will begin with asking the user for what the temperature they want to use and converts it to a float
while True:
userInput = input("Please enter the whole number value of the temperature. ")
try:
    temperature = float(userInput)
    break
except ValueError:
    print("Not a number")

#Next we will ask the user if they are using Fahrenheit and Celcius
unit = input("Is this celcius or fahrenheit? ")

#Checks to see if the unit used is  Celcius
if unit == "celcius"  or unit == "Celcius":
    celcius = temperature * 9/5 + 32.0
    print(celcius)
elif unit == "fahrenheit" or unit == "Fahrenheit":
    fahrenheit = (temperature - 32.0) * 5/9
    print(fahrenheit)
else:
    print("Invalid unit. Exiting program.")