Python: Function
Define Function
Here's a example of defining a function.
def ff(x, y): """ff(x, y) returns x+y.""" return x+y print(ff(3,4)) # 7
A string immediately following the function def
line is the function's documentation.
return
is optional. If a function does not return statement, it returns None
.
Unspecified Number of Positional Parameters (Aka Rest Parameters)
To define unspecified number of positional parameters, use
*name
as last item. Your function will receive it as a
Tuple
.
💡 TIP: this is useful if you need to define a function such as sum.
# function with unspecified number of args def ff(*x): # x is received as a tuple. return x rr = ff(5,6) print(rr) # (5, 6) print(type(rr)) # <class 'tuple'>
# example of position param with rest param def ff(a, *x): return [a, x] rr = ff(5, 6, 7) print(rr == [5, (6, 7)]) # [5, (6, 7)]