A function
in python is a block of code that can be called and executed from another location in the program or class.
# function definition
def function_name(params):
return value # optional return statement
# calling the function
function_name(params)
# function call with associative parameter variables
function_name(param1=value1, param2=value2)
Notes:
By default, functions can not access outside variables. To access global variables, you need to use the 'global' keyword in front of the variable name. Otherwise, those global variables will be initialized inside the function with local scope.
>>> def smaller_num(x, y):
... if x < y:
... return x
... else:
... return y
...
>>> small_num = smaller_num(5, 10)
>>> small_num
5
Here, at first, a function is defined that returns a smaller value comparing them. An object is created to call the function with parameters required by the defined function.