Python 中将多个变量与相同值进行比较

使用布尔值或运算符将多个变量与同一值进行比较,例如 if a == 'value' or b == 'value' or c == 'value':。 如果任何变量等于指定值,则表达式的计算结果为 True。

a = 'dev'
b = 'test'
c = 'ship'

# ✅ 检查多个变量之一是否等于一个值

if a == 'dev' or b == 'dev' or c == 'dev':
    # 👇️ this runs
    print('One or more of the variables is equal to dev')
else:
    print('None of the variables is equal to dev')

# -------------------------------------------------------

# ✅ 使用 `in` 检查多个变量之一是否等于一个值
if 'dev' in (a, b, c):
    print('One or more of the variables is equal to dev')

# -------------------------------------------------------

# ✅ 检查多个变量是否等于一个值
if a == b == c == 'dev':
    print('The variables are equal to dev')

# -------------------------------------------------------

# ✅ 使用“and”检查多个变量是否等于值
if a == 'dev' and b == 'dev' and c == 'dev':
    print('The variables are equal to dev')

我们使用布尔值或运算符来检查多个变量之一是否等于一个值。

如果满足 3 个条件中的任何一个,示例中的 if 块就会运行。

我们不必使用相等 == 运算符,我们可以使用任何其他比较运算符。

或者,我们可以使用 in 运算符。

要将多个变量与同一值进行比较:

  1. 将变量分组在一个元组中。
  2. 使用 in 运算符检查值是否包含在元组中。
  3. 如果值至少等于一个变量,则 in 运算符将返回 True。
a = 'dev'
b = 'test'
c = 'ship'

# ✅ 使用 `in` 检查多个变量之一是否等于一个值
if 'dev' in (a, b, c):
    print('One or more of the variables is equal to dev')

in 运算符测试成员资格。 例如,如果 x 是 t 的成员,则 x in t 的计算结果为 True,否则计算结果为 False

如果我们需要将多个变量与必须满足所有条件的相同值进行比较,请使用 and 运算符。

a = 'dev'
b = 'test'
c = 'ship'

if a == 'dev' and b == 'dev' and c == 'dev':
    print('The variables are equal to dev')

只有当所有变量都等于指定值时,if 块才会运行。

我们可以对不同的比较运算符使用相同的方法。

这是一个检查多个变量是否都大于 0 的示例。

a = 1
b = 2
c = 3

if a > 0 and b > 0 and c > 0:
    # 👇️ this runs
    print('The variables are all greater than 0')

如果需要检查多个变量是否等于一个值,请多次使用相等 == 运算符。

a = 'dev'
b = 'dev'
c = 'dev'

if a == b == c == 'dev':
    # 👇️ this runs
    print('The variables are equal to dev')

if 块仅在所有变量都存储指定值时运行。