Python User-Defined Functions

A function is a set of statements that perform a specific task, a common structuring element that allows you to use a piece of code repeatedly in different parts of a program. The use of functions improve a program’s clarity and comprehensibility and makes programming more efficient by reducing code duplication and breaking down complex tasks into more manageable pieces.

Functions are also known as routines, subroutines, methods, procedures, or subprograms.

They can be passed as arguments, assigned to variables, or stored in collections.

A user-defined Python function is created or defined by the def statement.

Syntax

def function_name(parameter list): 
    function body/statements

The indented statements make up the body of the function and are executed when the function is called. Once the function is called, parameters inside round brackets become arguments.

Example

def absolute_value(number): 
   if number >= 0:
   return number 
   else: 
   return -number 
print(absolute_value(3)) 
print(absolute_value(-5))

Output

 //In the above example, number is the parameter of the function absolute_value. It acts as a variable name and holds the value of a passed in argument. 
 3
 5

 

Functions can call other functions

Functions can perform different types of actions such as do simple calculations and print text. They can also call another function.

Example

def members_total(n): 
  return n * 3 
def org_total(m): 
  return members_total(m) + 5

print(org_total(2)) 
print(org_total(5)) 
print(org_total(10))

Output

 11 
 20
 35

 

Scope and lifetime of a local variable

  • A variable’s scope refers to a program’s sections where it is recognized.
  • Variables and parameters defined within a function have a local scope and are not visible from outside of the function.
  • On the other hand, a variable’s lifetime refers to its period of existence in the memory.
  • Its lifetime coincides with the execution of a function which ends when you return from the function.
  • A variable’s value is discarded once the return is reached and a function won’t be able to recall a variable’s value from its previous value.