无法获取用户输入的数据类型

2024-04-27 07:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取用户输入的数据类型,但是我在代码方面遇到了一些问题。我尝试了以下代码:

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()

但是在运行代码之前它给了我两个警告

  1. 局部变量user_input可能在赋值之前被引用
  2. 过于宽泛的异常子句,如未指定异常类,或指定为Exception

运行代码后,当我输入数字时,它会给我正确的值,但当我输入字符时,它会给我一个错误:

UnboundLocalError: local variable 'user_input' referenced before assignment

请帮忙


Tags: 代码用户inputrawreturndeftypeexception
1条回答
网友
1楼 · 发布于 2024-04-27 07:15:33

您需要在try-catch之外设置“用户输入”

例如:

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()

相关问题 更多 >