In this tutorial, we will learn how to check multiple values in an if condition in Python. This method can be helpful in simplifying complex conditional statements and making your code more readable. Python provides multiple ways to check multiple values in a single if condition using logical operators, in
keyword, and all
or any
functions.
Step 1: Using Logical Operators
Logical operators like and
, or
, and not
can be used to check multiple values in an if condition. Here’s an example of using the and
operator to check if two variables are greater than a specific value:
1 2 3 4 5 |
x = 5 y = 7 if x > 3 and y > 3: print("Both x and y are greater than 3") |
Output:
Both x and y are greater than 3
Similarly, you can use the or
operator to check if at least one of the variables meets a certain condition:
1 2 3 4 5 |
x = 2 y = 7 if x > 3 or y > 3: print("At least one of x or y is greater than 3") |
Output:
At least one of x or y is greater than 3
Step 2: Using the ‘in’ Keyword
The in
keyword can be used to check if a variable’s value exists in a list, tuple, or string. This can be helpful when checking multiple values in an if condition:
1 2 3 4 |
x = 5 if x in [3, 4, 5, 6]: print("x is in the given list") |
Output:
x is in the given list
Step 3: Using ‘all’ or ‘any’ Functions
The all
function checks if all elements in an iterable are true, while the any
function checks if at least one element is true. You can use these functions to check multiple values in an if condition:
1 2 3 4 5 |
x = 5 y = 7 if all(val > 3 for val in [x, y]): print("Both x and y are greater than 3") |
Output:
Both x and y are greater than 3
Similarly, you can use the any
function to check if at least one of the variables meets a certain condition:
1 2 3 4 5 |
x = 2 y = 7 if any(val > 3 for val in [x, y]): print("At least one of x or y is greater than 3") |
Output:
At least one of x or y is greater than 3
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
x = 5 y = 7 if x > 3 and y > 3: print("Both x and y are greater than 3") x = 2 y = 7 if x > 3 or y > 3: print("At least one of x or y is greater than 3") x = 5 if x in [3, 4, 5, 6]: print("x is in the given list") x = 5 y = 7 if all(val > 3 for val in [x, y]): print("Both x and y are greater than 3") x = 2 y = 7 if any(val > 3 for val in [x, y]): print("At least one of x or y is greater than 3") |
Output:
Both x and y are greater than 3 At least one of x or y is greater than 3 x is in the given list Both x and y are greater than 3 At least one of x or y is greater than 3
Conclusion
In this tutorial, we’ve seen how to check multiple values in if condition in Python using logical operators, the in
keyword, and the all
or any
functions. These methods can be helpful to simplify complex conditional statements and improve the readability of your code.