I wrote this function to get user input of an integer and two strings (letters C F or K) for a temperature conversion exercise. I want to control the specificity of the input, i.e. that only the correct letters are entered and not another using the exception handling try: except: statements. The inputs are passed to the print function regardless, so even if you input say a “D”. I tried many things, but I am totally drawing a blank. Please help, need try: except to help me understand this in Python. Thanks. The code:
def gettemp ():
while True:
tempin = input ("Enter temperature value:")
scalein = input ("Enter temperature scale (C/F/K):")
scaleout = input ("Enter scale to convert to (C/F/K):")
try:
tempin == int (tempin)
scalein == "C" or "F" or "K"
scaleout == "C" or "F" or "K"
return tempin, scalein, scaleout
except NameError:
print ("Please reenter:")
print (gettemp())
>Solution :
Your approach using or is wrong. Using or on strings will return the first non-falsey string, in your case scalein and scaleout will both become "C". Check if the scales are valid and raise an exception if they’re not:
def gettemp():
while True:
tempin = input("Enter temperature value:")
scalein = input("Enter temperature scale (C/F/K):")
scaleout = input("Enter scale to convert to (C/F/K):")
try:
tempin = int(tempin) # also make sure to use the right equals
valid = ("C", "F", "K")
if scalein not in valid or scaleout not in valid:
raise ValueError
return tempin, scalein, scaleout
except ValueError:
print("Please reenter:")
print(gettemp())
You can also achieve this behavior without using a try-except block:
def gettemp():
while True:
tempin = input("Enter temperature value:")
scalein = input("Enter temperature scale (C/F/K):")
scaleout = input("Enter scale to convert to (C/F/K):")
valid = ("C", "F", "K")
if not tempin.isnumeric() or scalein not in valid or scaleout not in valid:
print("Please reenter:")
continue
return int(tempin), scalein, scaleout
print(gettemp())