我正在尝试在python中创建一个程序,用户将输入温度,程序将温度转换为Kelvins。对于代码,我需要帮助检测输入无效的情况,如果输入无效则需要无返回值。
cas_number = "7732-18-5"
rho = 1000
mu = 1
Tm = 273.15
Tb = 373.13
k = 0.58
units = input("Input desired units, 'K' for Kelvin, 'C' for Celsius, and 'F' for Fahrenheit \n")
temperature = input("Input temperature value \n")
def check_units(units):
if units == 'F' or units == 'C' or units == 'K':
return True
else:
print("Invalid Input")
return False
def check_temperature(temperature):
try:
float(temperature)
return True
except:
return False
def convert_to_kelvin(temperature, units):
if check_temperature == True and check_units == True:
if units == 'K':
temperature = temperature
return temperature
elif units == 'C':
temperature += Tm
return temperature
elif units == 'F':
temperature = (temperature - 32)/1.8 + Tm
return temperature
else:
print("Invalid Input")
return
def is_gas(temperature):
if check_temperature and check_units:
if temperature >= Tb:
return True
elif temperature < Tb:
return False
else:
return None
def is_liquid(temperature):
if check_temperature and check_units:
if temperature > Tm and temperature < Tb:
return True
elif temperature <= Tm and temperature >= Tb:
return False
else:
return None
def is_solid(temperature):
if check_temperature and check_units:
if temperature <= Tm:
return True
elif temperature > Tm:
return False
else:
return None
答案 0 :(得分:0)
def check_units(units):
if units == 'F' or units == 'C' or units == 'K':
return True
else:
return None
测试check_units()
units = input("Input desired units, 'K' for Kelvin, 'C' for Celsius, and 'F' for Fahrenheit \n")
input_check = check_units(units) # calling the function
if input_check == True:
print('Valid input')
if input_check == None:
print('Invalid input')
你的check_temperature()搞砸了。获得输入后,您可以将其转换为float,如下所示:
temperature = input("Input temperature value \n")
temperature = float(temperature)
或者
temperature = float(input("Input temperature value \n"))