Currently, I have a function like so:
def my_func(*args):
#prints amount of arguments
print(len(args))
#prints each argument
for arg in args:
print(arg)
I want to put multiple arguments through to this function, but the following doesn't work for me. It gives out a syntax error on the asterisk * after the else.
my_func(
*(1, 2, 3, 4)
if someBool is True
else *(1, 2)
)
The workaround I found puts 1 and 2 in first and then puts 3 and 4 while checking for someBool.
my_func(
1, 2,
3 if someBool is True else None,
4 if someBool is True else None
)
I am fine with the above as my function checks for None but if there is an alternative I would gladly thank them.
Move the *
to outside the ... if ... else ...
:
my_func(
*((1, 2, 3, 4)
if someBool is True
else (1, 2))
)
You need an extra set of parenthesis. Also, you don't need to say is True
to check if a Boolean is "truthy" in python, making it: my_func(*((1, 2, 3, 4) if someBool else (1, 2)))
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.