如何自动判断用户输入类型?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 even0),literal_evalparses it correctly, and the function returns its absolute value. - If the user enters a quoted string (like
"hello"),literal_evalparses it as astrtype, and the function returns "Not possible". - If the user enters an unquoted string (like
hello) or invalid syntax, thetry-exceptcatches theValueErrorand 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

