【问题标题】:What is the proper syntax for grouping conditions in a if-statement in Python?在 Python 中的 if 语句中分组条件的正确语法是什么?
【发布时间】:2019-01-05 15:15:37
【问题描述】:

我无法完全理解 python 中 if 语句的语法。是否可以按如下所示对条件进行分组?

if my_age and neighborhood_age > 20:

python 是否会将上述代码完全理解为: if my_age> 20 and neighborhood_age > 20:?

如果它确实理解完全相同的东西,我如何对条件进行分组?例如:

假设我有三个条件:

my_age and neighborhood_age > 20 father_age < 60 cousin_age < my age

编写 if 语句的正确方法是什么? if (my_age and neighborhood_age &gt; 20) and (father_age &lt; 60) and (cousin_age &lt; my age):?

如果我开始混合使用“and”和“or”运算符会怎样?编写以下代码的最佳方法是什么:

if ((my_age and neighborhood_age &gt; 20) and (father_age &lt; 60) and (cousin_age &lt; my age)) or girlfriend_age &gt; 18:

【问题讨论】:

  • 您基本上已经掌握了所有语法,为什么不尝试运行它,看看会发生什么? (为了解决第一部分,不要写像if my_age and neighborhood_age &gt; 20这样的条件,你的第二个代码将是编写它的方式。if my_age&gt; 20 and neighborhood_age &gt; 20除此之外,它都是正确的。试试吧。
  • 如果我有几个变量来匹配一个条件,第二个例子效果很好,但是如果我想将几十个变量与一个值进行比较该怎么办?
  • python 提供了相当多的工具来处理多个条件。看看anyall 和成员资格测试in,它们可以使设置更复杂的条件变得微不足道。所有这些都需要先设置某种列表,然后检查变得容易。

标签: python if-statement syntax


【解决方案1】:

python 是否将上面的代码完全理解为:如果 my_age> 20 和neighbor_age > 20: ?

不,不会。 Python 会将其解释为:

if (my_age) and (neighborhood_age > 20)

如果你想比较两个值和第三个值,你必须这样做:

if (my_age > 20 and neighborhood_age > 20): ...

或者,为了绝对清晰而进行分组:

if ((my_age > 20) and (neighborhood_age > 20)): ...

如果要比较的值很多,可以使用all

if all(age > 20 for age in (my_age, neighborhood_age)): ...

至于你的最后一个例子,我可能会这样写,使用多行和括号来消除歧义:

if ((my_age > 20 and neighborhood_age > 20) and 
    (father_age < 60) and 
    (cousin_age < my age)
) or (girlfriend_age > 18):
    ...

除了最简单的情况外,几乎所有情况下,您都应该使用括号来明确您的意图。

【讨论】:

    【解决方案2】:

    您必须自己编写每个条件。 and 关键字与将if 语句放在if 语句中的含义相同。 例如:

    if my_age >= 20 and neighborhood_age >= 20:
        # Do something
    

    是一样的

    if my_age >= 20:
        if neighborhood_age >= 20:
             # Do something
    

    andor 混合使用更简洁的方法是使用好括号和结束行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多