How To Check Multiple Values In If Condition In Python

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:

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:

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:

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:

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:

Output:

At least one of x or y is greater than 3

Full Code

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.