【发布时间】: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 > 20) and (father_age < 60) and (cousin_age < my age):?
如果我开始混合使用“and”和“or”运算符会怎样?编写以下代码的最佳方法是什么:
if ((my_age and neighborhood_age > 20) and (father_age < 60) and (cousin_age < my age)) or girlfriend_age > 18:
【问题讨论】:
-
您基本上已经掌握了所有语法,为什么不尝试运行它,看看会发生什么? (为了解决第一部分,不要写像
if my_age and neighborhood_age > 20这样的条件,你的第二个代码将是编写它的方式。if my_age> 20 and neighborhood_age > 20除此之外,它都是正确的。试试吧。 -
如果我有几个变量来匹配一个条件,第二个例子效果很好,但是如果我想将几十个变量与一个值进行比较该怎么办?
-
python 提供了相当多的工具来处理多个条件。看看
any、all和成员资格测试in,它们可以使设置更复杂的条件变得微不足道。所有这些都需要先设置某种列表,然后检查变得容易。
标签: python if-statement syntax