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?
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.
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.
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.
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 .
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'.")
First thing that comes to mind:
if [a, b, c, d].count(True) > 1:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With