【发布时间】:2018-03-12 10:31:46
【问题描述】:
我正在尝试获取用户输入的数据类型,但我遇到了一些代码问题。我尝试使用以下代码:
def user_input_type():
try:
user_input = int(raw_input("Enter set of characters or digit"))
except:
try:
user_input = str(user_input)
except Exception as e:
print e
return type(user_input)
return type(user_input)
print user_input_type()
但它在运行代码之前给了我 2 个警告。
- 局部变量
user_input可能在赋值前被引用。 - 异常子句过于宽泛,例如未指定异常类,或指定为
Exception。
在我输入数字时运行代码后,它给了我正确的值,但是当我输入字符时,它给了我一个错误:
UnboundLocalError: 赋值前引用了局部变量 'user_input'
请帮忙。
【问题讨论】:
-
了解这些警告出现在哪一行总是有帮助的。您应该始终包含该信息。
-
这是因为
user_input在发生异常时不会被赋值。
标签: python python-2.7 try-except