【问题标题】:If conditional that checks on variable type (int, float, ect)如果有条件检查变量类型(int、float 等)
【发布时间】:2015-04-08 19:51:01
【问题描述】:

Python3:我想知道我是否可以设置一个 if 语句来像通常那样执行一些代码。

但我希望语句是这样的:(伪代码)

If variable1 !== "variable type integer":
    then break. 

这可能吗?谢谢您的帮助。

如果这个问题已经得到解决,我深表歉意,但搜索建议机器人没有任何帖子可以指向我。

杰西,NOOb

【问题讨论】:

  • 你有什么特别的语言吗?
  • 抱歉:是在 OSX yosemite 上运行的 Python3
  • 看起来像 javascript?您应该在帖子中添加 Python3 标签
  • 谢谢,了解这个。
  • 这不是 Python 中常见的模式 - 为什么你认为你需要这样做?

标签: python if-statement python-3.x


【解决方案1】:

您可以导入类型并根据它们检查变量:

>>> from types import *

>>> answer = 42

>>> pi = 3.14159

>>> type(answer) is int # IntType for Python2
True

>>> type(pi) is int
False

>>> type(pi) is float # FloatType for Python 2
True

对于您更具体的情况,您可以使用以下内容:

if type(variable1) is int:
    print "It's an int"
else:
    print "It isn't"

请记住,这是针对已作为正确类型存在的变量。

如果,正如您在评论 (if user_input !== "input that is numeric") 中所指出的那样,您的意图是尝试确定用户输入的内容对于给定类型是否有效,您应该尝试不同的方式,类似的方式的:

xstr = "123.4"             # would use input() usually.
try:
    int(xstr)              # or float(xstr)
except ValueError:
    print ('not int')      # or 'not float'

【讨论】:

  • pi 不是浮点型吗?如果我理解正确,这是从“类型”模块中提取的?基本上我只需要一种使用 if 来执行 break 语句的方法。 if user_input !== "输入数字"
  • @user3321476,是的,它是一个浮点类型,这就是为什么type(pi) is int 给你错误。我添加了特定于 Python3 的那些,将 Python2 降级为 cmets,并在底部为您提供了一个更具体的示例。
  • 甜,我现在明白了,你摇滚!
  • @user3321476,希望我能获得足够的支持和/或接受。轻推轻推,眨眼,眨眼:-)
【解决方案2】:

通常最好使用isinstance,这样你也可以接受像鸭子一样嘎嘎叫的变量:

>>> isinstance(3.14, int)
False
>>> isinstance(4, int)
True
>>> class foo(int):
...     def bar(self):
...         pass
... 
>>> f = foo()
>>> isinstance(f, int)
True

【讨论】:

    猜你喜欢
    • 2016-09-21
    • 2017-01-20
    • 2014-05-25
    • 2021-07-25
    • 2021-01-13
    • 2019-02-24
    • 2012-11-28
    • 1970-01-01
    • 2014-01-16
    相关资源
    最近更新 更多