Working with Functions in Python – Download Note pdf

Working with Functions in Python (A Complete Notes)


Functions – Introduction

Why do we need Functions?

It is easy to work with small problems because its solution is also small.  When the problem becomes complex, the size and complexity of the program also increased, and it becomes difficult and cumbersome for a programmer to manage data and control statements in the whole program.

At this stage, programmers start thinking of breaking a large program into several small programs.  Sometimes it works fine but, not solved their problems every time.

It creates another problem, in managing several program files, that are written for solving a single problem.

Functions: Definition

Python provides the features to divide a large program into different smaller modules, called Functions.

A Function is a group of statements i.e. subprogram, that exists within a program for the purpose of performing specific tasks, and returns values/results whenever it is required.

Functions can take some data as input, process upon according to the instructions, and give some output at the end.

Example – max( ), min( ), sum( ), type(), etc.

Types of Functions

In Python, Functions can be categorized into three categories-

  1. Built-in functions
  2. Functions defined in Modules
  3. User-defined Functions

(a) Built-in Functions

Built-in Functions are the predefined functions that are already available in Python. These functions are always available in the standard library, no need to import any module for them.

Most frequently used Built-in Functions

  1. int( ) – to convert into an integer.
  2. float ( ) – to convert into float.
  3. bool ( ) – to convert into Boolean.
  4. str ( ) – to convert into a string.
  5. list ( ) – to convert a sequence into a list.
  6. tuple( ) – to convert a sequence into a tuple.
  7. dict( ) – to convert sequences into the dictionary.
  8. input( ) – to input value as a string.
  9. eval(  ) – to evaluate strings in the form of expression.
  10. print( ) – to print/show output.
  11. range( ) – to define a series of numbers, useful for a loop.
  12. max( ) – to find the maximum numbers.
  13. min ( ) – to find the minimum numbers.
  14. sum( ) – to sum two numbers or a list or tuple.
  15. abs( ) – to find the absolute value (i.e. positive number) of numbers.
  16. round (n, p ) – rounds a given floating point number to the specified number of digits and returns the result.
  17. len( ) – returns the length of the sequence.
  18. chr( ) – returns the equivalent ASCII character of the given number.
  19. ord( ) – returns the ordinal value (ASCII number) of the given character.
  20. type ( ) – returns the data type of data or variable.
  21. id( ) – returns the memory reference of value or variable.

(b) Functions defined in Module

These functions are pre-defined in particular modules and can only be used when the corresponding module is imported.

For example,

  • randint() function of the random module,
  • pow() function of the math module,
  • mean() module of the statistics module,
  • dump() function of the pickle module,
  • reader() function of csv module,
  • connect() function of mysql.connector module.

(c) User-Defined Functions 

A function defined by the programmer or user i.e. you can create your own functions, called user-defined function.

For example, SimpleInterest(), Factorial(), LinearSearch(), etc.

User-Defined Functions

Creating a user-defined function:

A function is a set of statements that performs a specific task. Using functions in a program improves – the quality of the program, readability of the program, clarity of the program, reusability of code, and make ease of maintenance.

In Python, user-defined functions are defined (created) by

  • the def  statement followed by the function name and parentheses ‘()’, the colon ‘:’ 
  • and function body ( set of statements)
def  <function_name>( [parameters/arguments] ):
   [“““Functions Doc-Strings ”””]
   <statement>
   <statements>
   ………  
   [return value/variable/expression] 
  • def – is a keyword, that indicates the start of the function.
  • Function_name – uniquely identify function
  • Parameters – arguments are used to pass values to the function. It is optional.
  • Colon ( : )  – to mark end of function header
  • Doc-string – Documentation strings provide a convenient way of associating documentation with Python modules, functions, classes, and methods. print (functionname._ _ doc _ _ )
  • Statements- to make function body and implement the purpose of the function. Must be at the same indentation level (4 spaces)
  • return  – An optional statement is required when a function needs to return a value.

For Examples:

#Example 1
def Add2Numbers(a, b):
    c = a +  b
    print(c)

#Example 2 - returning a quotient
def quotient(a, b ):
     c = a / b
     return c

#Example 3- Increase the element of list by 2
def increseby2(lst):
     for i in range(len(lst)):
           lst[i] = lst[i] = 2


Calling / Invoking a Function

A function definition defines user-defined functions. The function definition does not execute the function body; this gets executed only when the function is called or invoked.

Calling of function means, invoking or accessing or using the function. To execute a function, invoke a function by its name and parameters inside the parenthesis (), if required.

Syntax:

  • Function_Name( )
  • Function_Name (arguments or parameters)
  • Res = Function_Name( )
  • Res = Function_Name( arguments / parameters)
 def sayHello( name ):
   “““ This func say hello”””
   print(“Hello Mr/Ms.”, name) 

 def calSum( x, y ):
   “““ Sum of two numbers”””
   return (x + y) 

 # Main Block
 print( "Testing of function")
 Name=input("Your name Plz")
 sayHello(Name)
 a = int(input("Number 1 plz :"))
 b = int(input("Number 2 plz: "))
 res = calSum(a, b)
 print("Sum of these numbers is ", res) 

The flow of Execution in a Function Call

The sequence of execution is:

1 -> 4 -> 9 -> 10 -> 11 -> 1 -> 2 -> 12 -> 13 -> 14 -> 4 -> 5 -> 6 -> 14 -> 15

Arguments and Parameters

Arguments: Values being passed by function call statement, are called arguments. Also called actual parameter or actual argument

calSum(a, b)  #here ‘a’ and ‘b’ are arguments

Parameters: Values being received by function definition statement, are called parameters. Also called formal parameter and formal argument.

def calSum(x , y ) :       # here ‘x’ and ‘y’ are parameters

We can pass values to functions to perform tasks according to values. In the function definition, variables are defined to receive values, and through a function call statement, values send to the function.

# function header – definition

def calSum(x , y ) :  
  return (x+y)

#function call – passing values to function

print(calSum(20, 30)  

a = 20
b = 30
c = calSum(a, b)  #function call – passing values to function
print(c)

Types of Arguments (Passing Parameters)

There are four types of formal arguments in Python.

  1. Positional Arguments (Required Arguments)
  2. Default Arguments
  3. Keyword (Named) Arguments
  4. Variable length Arguments

Positional Arguments

When the function call statement must match the number and order of arguments defined in the function definition,  such types of arguments are called Positional Arguments / Required Arguments / Mandatory Arguments.

The process of matching arguments is called Positional Argument Matching.

def showResult(name, math, comp):
    print("Name : ",name)
    print("Your Score")
    print("Math :", math)
    print("C.S. :", comp)

# Main Block 
showResult( “Amrit”, 85, 60)
showResult(60, “tanmay”, 85) 
showResult( “amrit”)	 #Mismatch number of arguments
showResult(85,36)  # Mismatch number of arguments

Default Arguments

Python allows us to assign default values(s) to a function’s parameter(s) which becomes useful when matching arguments is not passed in the function call statement.

Rules :

  • The default values are specified in the function header of the function definition.
    •     def showResult (name =‘Not Given’, math = 0, comp = 0) :
    •     def  power( b , p = 2) :
    •     def  interest (p , r = 10, t = 2):
  • Non–default arguments cannot follow default arguments i.e. any parameter can not have a default value unless all parameters appearing on its right have their default value.
    •     def showResult (name , math = 100 , comp,) : 
    •     def  power( b =10, p) :
    •     def  interest (p =1000, r , t = 2):
  • A parameter having a default value in the function header becomes optional in a function call.
    • showResult( )
    • showResult (“Mohit”, 50)
    • power(10)
  • The default values for parameters are considered only if no value is provided for that parameter in the function call statement.

Keyword (Named) Argument

The default arguments allow to specify the default value for the parameters, but it does not allow to pass the value by changing order i.e. arguments always passed in the same order.

Keyword arguments are the named arguments with assigned values being passed in the function call statement.

Keyword argument allows us to write any argument in any order with the help of an argument name.  Using keyword arguments, we can pass argument values by keyword i.e. by parameter name.

Example:

  • showResult ( math = 10, comp = 23, name =‘Sumit’)
  • interest  (r = 2, principal = 5000, t = 5)

Advantages:

  • No need to remember the order of the arguments.
  • No need to give value for all, specify only those which you want (if default value is mentioned for all).

Variable length arguments

Python allows us to pass variable number of arguments to a function, this is called Variable length argument.

Variable length arguments are declared with * (asterisk) symbol.

Example:

def Sum_all(*n):
    s = 0
    print(n)
    for i in n:
        s = s + i
    print("Sum :",s)

Sum_all(1,2,5,9,10) 

Output:

Sum : 27

Returning Values from Functions

In Python, Functions may or may not return a value. Based on returning values, there are two types of Functions.

  • Non-void Functions  –  Functions returning some values.
  • Void Functions – Functions not returning any values.

Non – Void Functions

The Functions that return some value / values as a result, is called as Non-void Functions. Functions can return value with the help of return statement. return is a Python keyword.

Functions returning a value are also known as Fruitful Functions.

Syntax:

def function_name (parameters) :

      statements

      retrun <value>

Types of Non–Void Functions
  • Functions returning one value.
  • Functions returning multiple values.
Function Returning Single Value

# Returning String value

def  hello (name) :

       return “Hello Mr./Ms. ” + name

print ( hello(“anjeev”) )

# Returning Number value

def  cube( n ) :

        c = n ** 3

        return c

print (cube(10))

# Returning Float value

def  si( p = 100.00, t=2, r=5) :

        interest = (p * r * t ) / 100.00

        return interest

print (si(1500.00, 3, 15))

# Returning Boolean value

def  isDigit( ch ) :

        return ( ch.isdigit() )

print ( isDigit(‘a’))

Function Returning Multiple Values

The Functions that return multiple values i.e. more than one value are called Multi–Value returning Functions. These are some examples of functions returning a single value.

Examples:

# Returning multiple values

def  arithCalc ( n1, n2) :

       return n1+n2, n1-n2, n1*n2, n1/n2

a = 10

b  = 5

sum , sub , mul , quo = arithCalc(a, b)

print( sum, sub, mul, quo)

# Returning multiple values as a tuple

def  cube3( a, b, c ) :

        return a**3, b**3, c**3

cube3No = cube3 (5, 7, 9)

print(cube3No)

Void Functions

The Functions that does not return any value, as a result, is called as Void Functions.  In this case no need to write return statement or you many write return statement without value.

Syntax:

Not having any return statement:

def function_name (parameters) :

      statements

# printing lines

def  printline ( ) :

       print ( “-” * 80)

print (“ Hello “)

printline( )

print (“Good Morning”)

Having return statement, but does not return any value:

def function_name (parameters) :

      statements

      retrun

# Replicate string 3 times

def  replicate( string ) :

        print (string * 3 )

        return

print( “Hello Dears All”)

replicate(“Thankyou”)

Scope of a Variable

Scope means the accessibility of variables in other parts of the program. The scope rules of Python, decide in which parts of the program a particular variable can be accessed or not.

Types of Scope

(a) Global Scope, and  (b) Local Scope

Global Scope:

A variable that is defined in the ‘main’ program, is called Global Variable and it has global scope.

Local Scope

A variable that is defined in the function called Local Variable and it has local scope.

Lifetime

The time for which a variable remains in memory is called Lifetime of Variable. It depends on the scope of the variable.

Examples-1:

#Local vs. Global

def check( ) :

      LAmount = 2500.00            #Local Variable

      print(“Inside Function Check”)

      print(LAmount)

      print(GNum)         

# Main block

GNum = 100                   #Global Variable

check()

print (“Inside the Main Block”)

print (GNum)

print (LAmount)                    #  NameError: name ‘LAmount’ is not defined

Examples-2:

# Local vs Global

def  check( ) :

      LAmount = 2500.00  #Local hides Global

      print(“Inside Function Check”)

      print(LAmount)

      print(GNum)                 

# main block

GNum = 100                            #Global Variable

LAmount = 200                         #Global Variable

check()

print( “Inside the Main Block” )

print(GNum)

print(LAmount)

Examples-3:

#Local vs. Global

SVar = 9999                             # Global Variable, for all

def  check( ) :

      LAmount = 2500.00       #Local Variable

      print(“Inside Function Check”)

      print(SVar)

      print(GNum)                 

      print(LAmount)

# Main block

GNum = 100                   #Global Variable

check()

print (“Inside the Main Block”)

print (GNum)

print (Svar)

global Statement

In Python, global statement allows us to use the same global variable inside the function. It does not allow functions to create another variable of the same name.  It means, listed identifiers are part of global namespace or global environment. Python uses LEGB namespace rule to search the identifier variable.

global  <variable name>

# it tell a function that a particular name do not create variable but use global variable.

Example:

# global Statement

def  check( ) :

      global num

      num = 9999  # It changes the global num

      amount = 222

      print(“Inside Check”)

      print(“num : “, num)

      print(“amount : “,amount)           

# main block

num = 100

amount = 200

print( “Main Block” )

print(“num : “, num)

print(“amount : “,amount)

check()

print( “Main Block” )

print(“num : “, num)

print(“amount : “,amount)

OUTPUT

Main Block

100

200

Inside Check

9999

222

Main Block

9999

200

LEGB (Local, Enclosing, Global, and Built-in ) Namespace: Name Resolution

To check every identifier, Python uses the LEGB name resolution rule. LEGB rules state that-

Local Environment – First check-in the local namespace or local function or local environment, found then use it, otherwise move to Enclosing environment,

Enclosing Environment – If not found in Local, then it checks inside the enclosing namespace, if found then ok, otherwise moves to the global namespace.

Global Environment – If not found in Enclosing, it checks inside the global namespace, if found then ok, otherwise move to the Built-in namespace.

Built-in Environment – If not found in Global, it checks inside the Built-in namespace, if found then ok, otherwise raises an Error message –

                                      NameError: name ‘varName’ is not defined.

Leave a Comment

You cannot copy content of this page

Scroll to Top