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.
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.
def absolute_value(number): if number >= 0: return number else: return -number print(absolute_value(3)) print(absolute_value(-5))
//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 perform different types of actions such as do simple calculations and print text. They can also call another function.
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))
11 20 35