Python温度转换输入合法性校验的异常处理问题求助
Python温度转换输入合法性校验的异常处理问题求助
Hey there! Let's break down what's going wrong with your code and fix it step by step—you're on the right track with try/except, just a few missteps in how you're validating inputs.
First, let's go over the key issues in your original code:
- Temperature conversion check:
tempin == int(tempin)doesn't actually convert the input to an integer, nor will it trigger an error properly. If the input isn't a number,int(tempin)will throw aValueError, but you're just doing a comparison here instead of attempting to assign the converted value. - Scale validation logic:
scalein == "C" or "F" or "K"is a common Python gotcha. This line doesn't check ifscaleinis one of those three letters—instead, it evaluates to(scalein == "C") or "F" or "K", and since non-empty strings are alwaysTrue, this condition will never fail no matter what you input. - Wrong exception type: You're catching
NameError, but that's for when you reference a variable that doesn't exist. The error you'll get from invalid numeric input isValueError. Also, invalid scale inputs aren't exceptions—they're just invalid values we need to check manually.
Here's a fixed version of your function that does proper input validation with try/except for the temperature and manual checks for the scales:
def gettemp(): while True: # Validate temperature input (must be integer) try: tempin = int(input("Enter temperature value: ")) except ValueError: print("Oops! That's not a valid integer. Please reenter.") continue # Validate input scale (handle case insensitivity and extra spaces) scalein = input("Enter temperature scale (C/F/K): ").strip().upper() if scalein not in ["C", "F", "K"]: print("Invalid input scale! Please use only C, F, or K.") continue # Validate output scale scaleout = input("Enter scale to convert to (C/F/K): ").strip().upper() if scaleout not in ["C", "F", "K"]: print("Invalid output scale! Please use only C, F, or K.") continue # All inputs are valid—return them return tempin, scalein, scaleout # Test the function print(gettemp())
Let me walk through what this does:
- Temperature validation: We wrap
int(input(...))in a try block. If the user enters something that can't be converted to an integer (like a string or decimal), it triggers aValueError, we print an error message, and the loop starts over. - Scale validation: We use
.strip().upper()to handle accidental spaces and case insensitivity (so users can enter lowercase c/f/k too). Then we check if the input is in our allowed list—if not, we prompt again. - Loop until valid: The
while Trueloop keeps running until all inputs pass validation, at which point we return the valid values.
This way, the function won't return anything until the user provides a valid integer temperature and valid scale letters.
备注:内容来源于stack exchange,提问作者Dr. H
相关产品推荐
相关产品推荐

