【问题标题】:Simple 'if' or logic statement in Python [closed]Python中的简单“if”或逻辑语句[关闭]
【发布时间】:2011-10-31 18:09:29
【问题描述】:

你会如何用 Python 编写以下代码?

if key < 1 or key > 34:

我已经尝试了所有我能想到的方法,但发现它非常令人沮丧。

【问题讨论】:

  • 你有什么问题?你得到哪个错误?在我看来,您的示例是有效的 python 代码!?
  • 您在寻找特定的语法吗?你写的关于的陈述是你将如何用Python写它。

标签: python if-statement logic


【解决方案1】:

这是一个布尔值:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

但是

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , 只有当 a 和 b 都为真时才为假

not (a or b) 只有当 a 和 be 都为假时才为真。

【讨论】:

    【解决方案2】:

    如果key 不是intfloat 而是string,则需要先将其转换为int

    key = int(key)
    

    或通过做float

    key = float(key)
    

    否则,您的问题应该有效,但是

    if (key < 1) or (key > 34):
    

    if not (1 <= key <= 34):
    

    会更清楚一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2016-07-29
      相关资源
      最近更新 更多