27
votes

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?

7

7 Answers

46
votes

What about this:

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.

19
votes

Another idea:

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

I'd probably write this as

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

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!"
2
votes

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
1
votes

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.

1
votes

Except that she's probably asking for this:

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