How to compare multiple variables to the same value?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)

Method 2

Another idea:

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

Method 3

I’d probably write this as

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

Method 4

If you have ten variables that you are treating as a group like this, you probably want to make them elements of a list, or values in a dictionary, or attributes of an object. For example:

my_dict = {'A': 1, 'B': 2, 'C': 3 }

if all(x > 2 for x in my_dict.values()):
    print "They're all more than two!"

Method 5

Depending on what you are trying to accomplish, passing a list to a function may work.

def foo(lst):
    for i in lst:
        if i < 2:
            return
    print lst

Method 6

How about:

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

For the general case, there isn’t a shorter way for indicating that the same condition must be true for all variables – unless you’re willing to put the variables in a list, for that take a look at some of the other answers.

Method 7

Except that she’s probably asking for this:

if A >= 2 and B >= 2 and C >= 2 and D >= 2:


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x