Python 无法获取用户输入的数据类型
我正在尝试获取用户输入的数据类型,但我在代码方面遇到了一些问题。我尝试了以下代码:Python 无法获取用户输入的数据类型,python,python-2.7,try-except,Python,Python 2.7,Try Except,我正在尝试获取用户输入的数据类型,但我在代码方面遇到了一些问题。我尝试了以下代码: 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:
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()
但在运行代码之前,它会给我两个警告
user\u input
exception
请提供帮助。您需要在
try catch
之外设置“用户输入”
Ex:
def user_input_type():
user_input = raw_input("Enter set of characters or digit") #---->Outside try-except
try:
user_input = int(user_input)
except:
try:
user_input = str(user_input)
except Exception as e:
print e
return type(user_input)
print user_input_type()
知道这些警告出现在哪一行总是有帮助的。您应该始终包含该信息。这是因为在发生异常时不会分配用户输入。不,这没有意义。相反,您应该在try外部执行
user\u input=raw\u input(…)
,然后在内部执行int
调用。@Rakesh,上面的代码不适合,因为如果用户输入字符,那么默认返回类型(None)将为str。此外,如果您尝试打印字符用户输入,如果用户输入非数字,则将打印“无”character@Pradeep. 如果用户输入一个字符,它将不是非类型