How to check multiple variables against a value in Python?

In this tutorial, we will learn how to check/test multiple variables against a value in Python? By IncludeHelp Last updated : September 18, 2023

Given multiple variables and they are assigned some values, we have to test a value with these variables.

Checking multiple variables against a value

Let, there are three variables a, b and c and we have to check whether one or more variables have the given value.

  1. Using or Operator
  2. Using in Operator
  3. Using == Operator

1) Using or Operator

The or operator returns true if one of the given conditions is matched. Consider the below example,

Example

a = 10
b = 20
c = 30

if a == 10 or b == 10 or c == 10:
  print("True")
else:
  print("False")

The output of the above program is:

True

2) Using in Operator

The in operator returns true if a value or sequence of values present in the object.

Example

a = 10
b = 20
c = 30

# way 1
if 10 in (a, b, c):
  print("True")
else:
  print("False")  

# way 2
if 10 in {a, b, c}:
  print("True")
else:
  print("False")  

The output of the above program is:

True
True

3) Using == Operator

The == operator can also be used to check a single value against multiple variables but in this case, we can check multiple variables with a single value.

Example

# multiple variables having 
# the same value
a = 10
b = 10
c = 10

if a == b == c == 10:
  print("True")
else:
  print("False")

# multiple variables having 
# the different values
a = 10
b = 20
c = 30

if a == b == c == 10:
  print("True")
else:
  print("False")

The output of the above program is:

True
False

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.