The*_*era 9 python if-statement function argument-passing
我需要检查是否定义了a,b,c和d中的多个:
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'.)
Run Code Online (Sandbox Code Playgroud)
我目前正在嵌套if语句,但这看起来很可怕.你能提出更好的建议吗?
Dun*_*can 16
尝试添加值:
if sum([a,b,c,d]) > 1:
print("Please specify at most one of 'a', 'b', 'c', 'd'.")
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为布尔值继承自int,但如果有人传递整数,它可能会被滥用.如果这是冒险将他们全部投入布尔人:
if sum(map(bool, [a,b,c,d])) > 1:
print("Please specify at most one of 'a', 'b', 'c', 'd'.")
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想要一个标志True:
if sum(map(bool, [a,b,c,d])) != 1:
print("Please specify exactly one of 'a', 'b', 'c', 'd'.")
Run Code Online (Sandbox Code Playgroud)