You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 a ValueError, 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 if scalein is one of those three letters—instead, it evaluates to (scalein == "C") or "F" or "K", and since non-empty strings are always True, 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 is ValueError. 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:

  1. 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 a ValueError, we print an error message, and the loop starts over.
  2. 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.
  3. Loop until valid: The while True loop 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 09:44:30