user defined functions in python


  • 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

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 function_name(parameter list):
        function body/statements

Example

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

Output

    3
    5