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

如何自动判断用户输入类型?Python数学函数兼容非数字输入问题

Hey there! Let's fix this issue together. The problem you're hitting is that literal_eval only works with valid Python literals — so if a user enters a plain string like hello (without quotes), it can't parse it and throws that ValueError. Plus, your type check can be improved for better flexibility. Here's how to handle this properly:

Step 1: Add Error Handling for Invalid Inputs

Wrap the literal_eval call in a try-except block to catch cases where the input can't be parsed as a valid literal. This covers things like unquoted strings, typos, or other non-literal inputs that would break the parser.

Step 2: Use isinstance for Type Checking

Instead of checking type(x) == int or type(x) == float, use isinstance(x, (int, float)). This is the standard Python way to check types because it accounts for inheritance (e.g., if you ever have a custom numeric type that inherits from int, it will still be recognized correctly).

Full Working Code

from ast import literal_eval

def distance_from_zero(x):
    # Check if input is an integer or float
    if isinstance(x, (int, float)):
        return abs(x)
    else:
        return "Not possible"

try:
    # Get input and parse it safely
    user_input = input("Please enter a number or value: ")
    parsed_input = literal_eval(user_input)
    print(distance_from_zero(parsed_input))
except ValueError:
    # If parsing fails, it's not a valid literal — return the error message
    print("Not possible")

How This Works

  • If the user enters a valid number (like 42, -3.14, or even 0), literal_eval parses it correctly, and the function returns its absolute value.
  • If the user enters a quoted string (like "hello"), literal_eval parses it as a str type, and the function returns "Not possible".
  • If the user enters an unquoted string (like hello) or invalid syntax, the try-except catches the ValueError and immediately returns "Not possible".

Note: If you're still using Python 2, replace input() with raw_input() — but Python 2 is end-of-life, so upgrading to Python 3 is recommended!

内容的提问来源于stack exchange,提问作者sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:08:21