Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python if more than one of N variables is true

I need to check if more than one of a, b, c, and d are being defined:

def myfunction(input, a=False, b=False, c=False, d=False):
    if <more than one True> in a, b, c, d:
    print("Please specify only one of 'a', 'b', 'c', 'd'.)

I am currently nesting if statements, but that looks horrid. Could you suggest anything better?

like image 522
TheChymera Avatar asked Nov 17 '14 15:11

TheChymera


People also ask

How do you check if multiple items are true 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 check if 3 values are the same in Python?

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 . For instance, there is no difference between the two expressions whenever b is a pure function with no side-effects.

How do I check if a condition is true in Python?

You can check if a value is either truthy or falsy with the built-in bool() function. According to the Python Documentation, this function: Returns a Boolean value, i.e. one of True or False . x (the argument) is converted using the standard truth testing procedure.

How do you check if multiple values are none in Python?

To check if multiple variables are not None: Wrap the variables in a sequence (e.g. a tuple or a list). Use the not in operator to check if None is not a member of the sequence. If the sequence doesn't contain None , then the variables are not None .


2 Answers

Try adding the values:

if sum([a,b,c,d]) > 1:
    print("Please specify at most one of 'a', 'b', 'c', 'd'.")

This works because boolean values inherit from int, but it could be subject to abuse if someone passed integers. If that is a risk cast them all to booleans:

if sum(map(bool, [a,b,c,d])) > 1:
    print("Please specify at most one of 'a', 'b', 'c', 'd'.")

Or if you want exactly one flag to be True:

if sum(map(bool, [a,b,c,d])) != 1:
    print("Please specify exactly one of 'a', 'b', 'c', 'd'.")
like image 57
Duncan Avatar answered Oct 06 '22 01:10

Duncan


First thing that comes to mind:

if [a, b, c, d].count(True) > 1:
like image 27
Rusty Avatar answered Oct 06 '22 01:10

Rusty