【问题标题】:How to use if/and? [duplicate]如何使用 if/and? [复制]
【发布时间】:2021-08-12 15:22:12
【问题描述】:

我正在尝试将 if 函数与“and”一起使用。它不起作用 - 有没有更好的方法或更好的命令?这是我的代码示例:

        if measure >= 4.52 and <= 4.58:
            optimal += measure
            total += measure
            count += 1
        elif measure >= 4.50 and <= 4.60:
            allowed += measure
            total += measure
            count += 1
        else:
            faulty += measure
            total += measure
            count += 1

感谢您的帮助!

【问题讨论】:

  • 已经有一个完美的答案。但是如果你想要elif 4.60&gt;=measure &gt;= 4.50 and ,你可以跳过and

标签: python if-statement


【解决方案1】:

您需要在 if 条件中重复 measure。像这样:

        if measure >= 4.52 and measure <= 4.58:
            optimal += measure
            total += measure
            count += 1
        elif measure >= 4.50 and measure <= 4.60:
            allowed += measure
            total += measure
            count += 1
        else:
            faulty += measure
            total += measure
            count += 1

【讨论】:

  • 谢谢你,这行得通!
【解决方案2】:

问题不在于if,而在于and。将if 从图片中取出一秒钟:

>>> measure = 4.53
>>> measure >= 4.52 and <= 4.58
  File "<stdin>", line 1
    measure >= 4.52 and <= 4.58
                         ^
SyntaxError: invalid syntax

它是无效的,因为 &lt;= 4.58 本身不是一个有效的声明。

>>> measure >= 4.52 and measure <= 4.58
True

现在您有一个有效的布尔语句(由anding 其他两个布尔语句一起生成),您可以在if 语句中使用它:

>>> if measure >= 4.52 and measure <= 4.58:
...     print("success!")
... 
success!

如果你想检查一个值是否介于其他两个值之间,你根本不需要and;您还可以将不等式运算符组合成一条语句,如下所示:

>>> 4.52 <= measure <= 4.58
True

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2015-02-05
  • 2014-11-07
  • 1970-01-01
  • 2014-10-25
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
相关资源
最近更新 更多