Functions In Python

Functions are indispensable abstractions in any modern Programming Language. Python is not an exception too. Writing functions in Python is very simple.

Every day thousands of Python functions are written.

Functions have got their original inspiration from Mathematics. In Mathematics, a function f(x)=y, will transform the input x into output y.

Just like a mathematical function, a Python function as well takes an input, applies an algorithm and returns a value.

When functions are provided by the Python Implementation they are called built-in functions.

When the functions are written by python programmers they are called user-defined functions.

Defining a function in Python - Syntax:

def function_name(param1,param2):

    python statement1

    python statement2

    <raise exception>

    .

    .

    .

    return <return  value>

 

Semantics of a Python function:

  • "def" is the keyword that starts a function definition. 
  • The "def" keyword stands for "defining" or "definition" of a function here.
  • The def keyword is followed by the name of the function and a colon(:).
  • The function accepts zero or more parameters.
  • The parameters are specified inside the parenthesis.
  • If a Python function does not accept any parameters, empty parenthesis needs to be provided after the python function name.
  • Python function definitions without the parenthesis result in syntax error.
  • The parameters to the functions generally are called the input to the functions or in-paramaters.(If the parameters are objects and they are read first and modified, then they are called inout-parameters, if they are only modified they are called out-parameters)
  • In Python, The block of statements following the function names form the body of the function.
  • The parameters of python functions are passed by value if they are of simple types and passed by reference if they are objects (references).

 

Quick Primer on the semantics of passing parameters:

Pass by Value: The modifications done to a variable inside a function are not reflected outside the scope of the function body. Because only a copy of the variable is passed, not the variable itself.

Pass by Reference: The modifications done to a variable inside a function are reflected outside the scope of the function body. Because the reference to the variable itself is passed.

 

  • Specific values for a function parameter are called as arguments. e.g., Temperature is a parameter where as 90.1 is a valid argument for the Temperature parameter.
  • A Python function may or may not return a value.
  • Together - the "def" keyword, function name and the return value - is called the method signature, or simply the syntax of a function. 
  • A python function can raise an exception at any point in time during its execution.
  • A function is executed only if that function is invoked. Having the definition of a function alone will not result in the execution of the function.
  • A function is called by specifying the name followed by parameters specified inside the parenthesis.

Python Functions - Example1 : A simple function 

#function definition starts in next statement

def SimpleFunction():

    print("I am printed inside a simple python function")

#function definition ended in previous statement

#Main program flow starts here

#calling a python function

#(Also called function invocation)

SimpleFunction()

 

Output:

I am printed inside a simple python function

 

Python Functions - Example2 : A function that takes parameters and returns value

#Function definition - (Starts in next python statement)

def Sum(Value1, Value2):

    SumValue = Value1 + Value2

    return SumValue

#Function definition - (Ended in previous python statement)  

 

#Main program flow starts here 

x = 10

y = 20

 

#Function invocation

SumTotal = Sum(x,y)

print("Sum of {} and {} is: {}".format(x,y,SumTotal))

Output:

Sum of 10 and 20 is: 30

Python Functions - Example3 : Call by Value

#Function definition starts in next statment

def callbyvalue(Number1,Number2):

    Number1 = Number1+10 # Modify the value of Number1

    Number2 = Number2+20 # Modify the value of Number2

#Function definition ended in previous statment

 

#Main flow starts here

x = 100

y = 200

callbyvalue(x,y)

#check weather x, y values have changed

print(x,y)

Output:

100 200

In the program above, The function callbyvalue(x,y) was passed of two arguments by taking a copy of X and Y values. Hence, even though the function modifies the values passed from the main program, it is not reflecting in the output.

Python Functions - Example4 : Call by Reference

#Function definition starts in next statment

def CallByReference(TopicList):

    if len(TopicList) is not 0:

        TopicList.pop(0)

#Function definition ended in previous statment       

#Main program flow starts here

PythonClasses = ["control flow", "functions", "classes","threads"]

 

#This function call will remove an entry from PythonClasses

CallByReference(PythonClasses)

 

# Check the effect of call by reference - the original object contents are modified

print(PythonClasses)

Output:

['functions', 'classes', 'threads'])

In the above call-by-reference example, PythonClasses is a reference to an object of type list that in turn contains string literals. Hence, the reference to the object itself is passed inside the function - when modifications are done on the contents of the object, it just reflects in any scope. The invariants of the object or state of the object is modified permanently when the content modifications are done through call-by-reference.

Python Functions - Example5 : A function that raises an Exception

def ProcInts(Integer1, Integer2):

    if isinstance(Integer1, int) is False or isinstance(Integer2, int) is False :

        raise Exception("ProcInts accepts only numbers")

    print("Success:ProcInts")

#Main program flow starts here

ProcInts(1,2)

ProcInts("One","Two")

Output:

Success:ProcInts

Traceback (most recent call last):

  File "function.py", line 42, in <module>

    ProcInts("One","Two")

  File "function.py", line 38, in ProcInts

    raise Exception("ProcInts accepts only numbers")

Exception: ProcInts accepts only numbers

 

The above python program shows how to raise an exception from a function definition. The raise keyword is used to raise an Exception. Since the exception is not handled anywhere in the program, the exception causes the program to terminate.

Default Parameters in Python Functions


Copyright 2023 © pythontic.com