In lua I can express this:
function f(arg)
N = arg or 0
print(N)
end
F()
F(5)
Output:
--> 0
--> 5
Is there a way to do that in python... instead of:
arg = None
If arg:
N = arg
else:
N = 0
--> n = 0
-- set arg to 5
--> n = 5
Just curious, I like the Lua 1 line implementation of that. The other one is kinda jank to me.
CodePudding user response:
Here is my real issue:
def f(number,*args):
if args:
N = args[0]
else:
N= 0
.... so on and so on
If I try:
def f(number,*args):
N = args[0] or 0
This returns out of range error.
For context: I was just playing around with recursion. This function on first run doesn't get passed args. It then gets passed args after the recursion.
CodePudding user response:
you can use or the other way around like this:
def f(arg=None):
N = arg or 0
print(N)
f() # 0
f(5) # 5
The second option is chosen whenever arg is False or None. https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
EDIT: You are looking for next
N = next(iter(args), 0)
args
is a tuple of all the additional parameters passed to your function. You can use next
in combination with iter
to iterate over those parameters and select the next/first, if it exists. If not, a default value gets assigned to N (in this case 0).
Its similar to N = args[0] if len(args) > 0 else 0
but without the check. Some more explanation is here for example.