【问题标题】:Why doesn't type() work in if statements in Python? [duplicate]为什么 type() 在 Python 的 if 语句中不起作用? [复制]
【发布时间】:2022-12-04 10:51:35
【问题描述】:
user_input = int(input('Enter input: '))

if type(user_input) == "<class 'int'>":
    print('This is a integer.')

上面的代码没有向控制台输出任何内容。我只是感到困惑,因为它非常简单并且看起来应该可以工作。

我试过删除输入行中不输出任何内容的 int() ,我理解这一点,因为 user_input 变成了一个字符串,但我不明白为什么当 user_input 被定义为整数时它不输出任何内容。

【问题讨论】:

  • 使用isinstance(user_input,int)。不要将类型与字符串表示混淆。在这种特殊情况下,类型检查毫无意义。如果上面的行没有抛出错误,那么 user_input 当然是一个 int。一个更好的方法来做你似乎想做的事情是在试图将字符串转换为 int 的行周围使用 try ... except 块。
  • 因为没有类型可以等于任何字符串,出于同样的原因,没有整数可以等于任何字符串。类型本身有自己的类型。
  • (有些人会建议依赖 try-except 是不好的,你应该使用像 isdigit 这样的字符串方法。那些人错了 - 这些方法检查字符属性,而不是字符串是否可以解析为 int。你会失败在像-3 这样的输入上,因为- 不是数字。与让int 处理它相比,尝试手动正确地检查是不必要的容易出错的情况,如果你尝试,情况会变得更糟解析浮点数而不是整数。)

标签: python if-statement input types conditional-statements


【解决方案1】:

使固定

那是因为type(user_input) 返回的是type,而不是字符串,不要将自己与看到的印刷品和真实的东西混淆。当你打印一些东西时,你只会看到表示的事情。只有它是一个字符串,你可以直接复制和比较它

print(type(type(user_input)))  # <class 'type'>

所以你很清楚,这就是使用type的方式

if str(type(user_input)) == "<class 'int'>":
    print('This is a integer.')

if type(user_input) == int:
    print('This is a integer.')

if type(user_input) is int:
    print('This is a integer.')

提升

首选方法应该是

if isinstance(user_input, int):
    print('This is a integer.')

【讨论】:

    【解决方案2】:

    这是因为你将它与错误的事物进行比较。如果你做了“type(user_input) == int”你的程序应该按预期工作。

    【讨论】:

      【解决方案3】:

      您可以使用上面提到的 isinstance 方法,或者直接与 str 进行比较,例如:

      user_input = int(input('Enter input: '))
      if type(user_input) is "int":
         print('This is a integer.')
      

      【讨论】:

        猜你喜欢
        • 2021-01-28
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2014-01-17
        • 2021-11-14
        相关资源
        最近更新 更多