In Python, functions are defined by def followed by the function name and arguments and a colon ( : ), next line starts the intended block (4 spaces) of commands. The result of a function is given back with return. The function definition ends with the end of the intended block.
Simple Example
def my_func(x,y):
z = x + y
return z
run the function
z = my_func(2,3)
print(z)
Predefined default argument values
def my_func(x=2,y=3):
return x+y
z = my_func()
Keyword arguments
better readable; argument order can be changed
z = my_func(x=2,y=3) # same as
z = my_func(2,3)
Multiple results
def my_func(x=2,y=3):
return x+y, x-y, x*y
z_sum, z_sub, z_prod = my_func(x,y)
Many arguments
to catch non-keywords arguments
def my_func(*args):
print(args)
to catch keyword arguments
def my_func(**args):
print(args)
z = my_func(a='test',b='m1',c=4,d=10)
Help description
def my_func(x,y):
'''
Example of a python function
'''
z = x + y
return z
help(my_func)