2017-10-08 82 views
-1

我想在python中創建一個程序,用戶將輸入一個溫度,並有程序單位將溫度轉換爲Kelvins。對於代碼,我需要幫助檢測哪個輸入無效,如果輸入無效,則返回無返回值。Python:用戶輸入和無效返回

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

你怎麼稱呼一個功能? –

+0

如果您想調用'check_units',只需執行'variable_name = check_units(units)','variable_name'就是您想要的名稱。 –

回答

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()被搞砸了。當您得到輸入,你可以將它轉換爲浮動,就像這樣:

temperature = input("Input temperature value \n") 
temperature = float(temperature) 

或者

temperature = float(input("Input temperature value \n"))