Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare multiple variables to the same value in "if"? [duplicate]

Tags:

python

I am using Python and I would like to have an if statement with many variables in it.

Such as:

if A, B, C, and D >= 2:     print (A, B, C, and D) 

I realize that this is not the correct syntax and that is exactly the question I am asking — what is the correct Python syntax for this type of an if statement?

like image 399
chingchong Avatar asked Dec 27 '11 04:12

chingchong


People also ask

How do you compare multiple values in an if statement?

To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.

How do you write a condition that checks whether the values of the variables a and b are the same in C ++?

(a==b) will be compared first and return either 1 (true) or 0 (false). Then value of variable c will be compared with the result of (a==b).

How do I test multiple variables in Python?

To test multiple variables x , y , z against a value in Python, use the expression value in {x, y, z} . Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.

How do you compare three variables in Python?

Python chains such relational operators naturally (including in and is ). a() == b() == c() is functionally equivalent to a() == b() and b() == c() whenever consecutive calls to b return the same value and have the same aggregate side effects as a single call to b .


1 Answers

You want to test a condition for all the variables:

if all(x >= 2 for x in (A, B, C, D)):     print(A, B, C, D) 

This should be helpful if you're testing a long list of variables with the same condition.


If you needed to check:

if A, B, C, or D >= 2: 

Then you want to test a condition for any of the variables:

if any(x >= 2 for x in (A, B, C, D)):     print(A, B, C, D) 
like image 182
Limbo Peng Avatar answered Sep 25 '22 08:09

Limbo Peng