I know you are already familiar with if condition in python to run the specific code of block based on the conditions. If the conditions are true then it will return true and run the code block.
But maybe you don’t know how to use
any() methods if you are checking multiple conditions in the same process. So in this trick, I will show you how you can check multiple conditions using the all() and any() methods with the help of a python list.
Yes, you can use the python list to check the multiple if conditions. You need to make a python list of all conditions as you make a normal list. Then you can use that list with all() and any() methods to check the conditions.
Let’s see the all() and any() methods with if condition.
Check All Conditions True
In this case, we will check the all conditions are true. For this, we will use all() methods in if condition using the python list.
So create a list of conditions and run the all() method with if a condition like the following code example.
Don’t do like this
Do like this
In the above example, we declare the variable of marks and then make a python list of conditions that are checking the student is passing or not. Then we use the all() method to check these conditions and return a result accordingly.
Note: all() method have to fulfill all the conditions true.
Check Any Conditions True
Now, what if you want to check that if any condition is true then return the result. Then you have to use the python any() method.
Same as above we will create a list of conditions using the comma separate then check these conditions in if condition using the any() method and that list.
See the following example code.
In the above code, we use the any() method using the python list to check if any condition is true then return the result.
Note: any() method have to fulfill any conditions true.
Thus, you can check as many conditions using the python list and then check that list with
Being Tricky 😉