📜  如何根据Python中的值检查多个变量?

📅  最后修改于: 2022-05-13 01:54:53.311000             🧑  作者: Mango

如何根据Python中的值检查多个变量?

给定一些变量,任务是编写一个Python程序来根据一个值检查多个变量。在Python中有三种可能的已知方法来实现这一点:

方法一:使用 or运算符

这非常简单明了。以下代码片段说明了此方法。

示例 1:

Python3
# assigning variables
a = 100
b = 0
c = -1
 
# checking multiple variables against a value
if a == -1 or b == 100 or c == -1:
    print('Value Found!')
else:
    print('Not Found!')


Python3
# assigning variables
a = 100
b = 0
c = -1
 
# checking multiple variables against a value
if a in [100, 0, -1]:
    print('Value Found!')
else:
    print('Not Found!')


Python3
# assigning variables
a = 90
 
# checking multiple variables against a value
if a not in [0, -1, 100]:
    print('Value Found!')
else:
    print('Not Found!')


Python3
# assigning variables
a = 9
b = 9
c = 9
 
# checking multiple variables against a value
if a == b == c == 9:
    print('Value Found!')
else:
    print('Not Found!')


输出:

Value Found!

方法#2:使用in关键字

它通常用于搜索序列,但可以很好地替换上面的代码。

蟒蛇3

# assigning variables
a = 100
b = 0
c = -1
 
# checking multiple variables against a value
if a in [100, 0, -1]:
    print('Value Found!')
else:
    print('Not Found!')

输出:

Value Found!

您也可以将它用于反语句:

示例 2:

蟒蛇3

# assigning variables
a = 90
 
# checking multiple variables against a value
if a not in [0, -1, 100]:
    print('Value Found!')
else:
    print('Not Found!')

输出:

Value Found!

方法 #2:使用 ==运算符

当使用单个值检查时,此方法仅适用于多个变量。

示例 1:

蟒蛇3

# assigning variables
a = 9
b = 9
c = 9
 
# checking multiple variables against a value
if a == b == c == 9:
    print('Value Found!')
else:
    print('Not Found!')

输出:

Value Found!