【问题标题】:Unable to get the type of data user inputs无法获取用户输入的数据类型
【发布时间】: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 个警告。

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

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

UnboundLocalError: 赋值前引用了局部变量 'user_input'

请帮忙。

【问题讨论】:

  • 了解这些警告出现在哪一行总是有帮助的。您应该始终包含该信息。
  • 这是因为user_input在发生异常时不会被赋值。

标签: python python-2.7 try-except


【解决方案1】:

您需要在try-catch 之外设置“user_input”。

例如:

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

【讨论】:

  • 不,这没有意义。相反,您应该在尝试之外执行user_input = raw_input(...),然后在内部执行int 调用。
  • @Rakesh,上面的代码是不合适的,因为如果用户输入字符,那么它默认返回类型(无),它将 str。另外,如果您尝试打印用户输入的字符,如果用户输入非数字字符,它将打印 None
  • @Pradeep。如果用户输入一个字符,它将不是 NoneType
猜你喜欢
  • 1970-01-01
  • 2011-08-19
  • 2019-12-04
  • 2021-09-28
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多