简体   繁体   中英

Python: User Input and Invalid returns

I'm trying to create a program in python where the user will enter a temperature and units having the program convert the temperature to Kelvins. For the code, I need help on detecting the case where either input is invalid, and having a None return value if the input is invalid.

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
def check_units(units):
    if units == 'F' or units == 'C' or units == 'K':
        return True
    else:        
        return None

Test the 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')

Your check_temperature() is messed up. After you get the input, you can convert it to float, like so:

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

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM