Sometimes you may need to test multiple variables against a value in Python. There are multiple ways to do this in Python. In this article, we will look at the different ways to test multiple variables against a value in Python.
How to Test Multiple Variables against a Value in Python
Here are the different ways to test multiple variables against a value in python.
Let us say you have 3 variables x=1, y=2, z=3.
Here is how to test variables x, y, z against value 0
if x==0 or y==0 or z==0: #do something print 'exists'
In the above statement, python will sequentially test each variable’s value and proceed further at the first condition that evaluates to be true. However, this can be tedious if you have too many variables to be tested.
Also read : How to Grep Multiple Strings & Patterns in Linux
In such cases, you can test the variables using the containment test
if 0 in (x,y,z): #do something print 'exists'
In the above case, python checks if 0 is present in the tuple containing x, y, z.
Similarly, you can also use the above following statement using curly braces ‘{ }’ instead of round braces.
if 0 in {x,y,z}: #do something print 'exists'
That’s it. As you can see it is very easy to test multiple variables in python.
Also read : How to Search in Nano Editor in Linux
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.