ScanSkill

function

A function in python is a block of code that can be called and executed from another location in the program or class.

Syntax

# 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:

  • It is used to reduce the repetition of codes.
  • A function either returns nil, a value, or an array of values.
  • When declaring a function, parameters can be passed as regular variables (no prefix to the variable), tuples for a variable number of args (using a single asterisk prefix *), or as a dictionary (using a double asterisk prefix **).

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.

Example

>>> 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.