How To Test Multiple Variables Against A Single Value In Python

Test multiple variables against a single value in Python

Let’s follow this tutorial to learn how to test multiple variables against a single value in Python with the explanation and examples below. It’s helpful for you.

What is a variable in Python

A variable in Python is a container which stores the value of the data.

Look at the example below to learn more about the variable.

title = 'Title: How To Test Multiple Variables Against A Single Value In Python.\n'
a = 4722 # a is of type int
b = 47.22 # b is of type float
c = 'Learn To Share IT' # c is of type str

print(title)
print(a)
print(b)
print(c)

Output

Title: How To Test Multiple Variables Against A Single Value In Python.

4722
47.22
Learn To Share IT

Test multiple variables against a single value in Python

These are some solutions that can help you test multiple variables against a single value in Python.

Solution 1: Using the in operator

The in operator returns True if a value is present in the object, otherwise returns False.

Syntax:

a in b 

Parameters:

  • a: The value you want to check.
  • b: The object.

Return value:

True or False.

Look at the example below to learn more about this solution.

a = 'Learn To Share IT'
b = 'Variables'
c = 'crvt4722'
d = 'Solution'

# Using a list to store data you can use tuple or set to store these data instead
arr = [a, b, c, d] 

# Create the function to test multiple variables against a single value
def myFunc(x, arr):
    if x in arr:
        print('Variable x is present in arr.')
    else:
        print('Variable x is not present in arr.')

x = 'crvt4722'
myFunc(x, arr)

# Test with another value
x = 'LearnShareIT'
myFunc(x, arr)

Output 

Variable x is present in arr.
Variable x is not present in arr.

Solution 2: Using the for loop 

You can use the operator == to check if each element in the multiple variables is equal to the given value or not.

Look at the example below.

a = 'Learn To Share IT'
b = 'Variables'
c = 'crvt4722'
d = 'Solution'

arr = [a, b, c, d] 

# Create the function to test multiple variables against a single value
def myFunc(x, arr):
    if x in arr:
        print('Variable x is present in arr.')
    else:
        print('Variable x is not present in arr.')

x = 'crvt4722'
myFunc(x, arr)

# Test with another value
x = 'LearnShareIT'
myFunc(x, arr)

Output 

Variable x is present in arr.
Variable x is not present in arr.

Summary 

To test multiple variables against a single value in Python, you can use the in operator or using for loop. These methods are beneficial in solving this problem. Choose the solution that is the best for you. We hope this guide is helpful to you. Thanks!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *