Working With Functions
Definition
• Definition: A function is sub program that
acts on data and often returns a value.
Or
• Function is a named sequence of
statements used to perform specific task
when it is invoked. Functions may or may
not return value.
Advantages - Function
• Use of functions enhances the readability of a
program.
• A big code is always difficult to read. Breaking the
code in smaller parts called Functions, keeps the
program organized, easy to understand and makes it
reusable.
• Functions are used to achieve modularity and
Types of Functions
Python Functions can be divided into three
categories:
1. Built-in Function : It is already defined and
ready to use.
2. Function defined in Module : These function
are pre-defined for particular module.
3. User defined function : It is define by the user
or programmer.
Built-in Functions
• These functions are built into Python and
can be accessed by a programmer. We
don’t have to import any module (file) to
these functions.
• Examples are type(), ord(), int(), input(),
print(), float() etc.
Functions in Modules
• Module is a file containing python
functions and statements.
• We can use these modules in our python
code, for this, a programmer needs to
import the module.
• Example math, pickle, csv, os etc
Importing entire module
• By using import statement
It is simple & most commonly
used way to use modules in python code.
Syntax:
import modulename1 [,
modulename2,…….]
Using import statement
Example:
>>>import math
>>>math.sqrt(100)
10.0
>>>math.fabs(-9.5)
9.5
Importing select object from a module
• It is used to get a specific function instead of
the complete module file.
• If we know beforehand which function(s),
we will need in code, then we may use from.
• For modules having large number of
functions, it is recommended to use from
instead of import.
Using from keyword with import
Syntax:
>>>from modulename import
functionname [, functionname…..]
Example:
>>> from math import sqrt
>>>sqrt(100)
10.0
Contd...
>>>fabs(-9.5)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in
<module>
fabs(-9.5)
NameError: name 'fabs' is not defined
>>>
User defined function
• User defined User defined functions are
those functions which are defined by the
programmer for their convenience.
• To define a function def keyword is used.
Contd...
• Syntax:
def <function name> ([parameter 1,
parameter 2,…..]) :
Set of instructions to be executed
[return ]
Point to remember while creating a
user defined function
• Function header always ends with a colon (:).
• The items enclosed in "()" are called
parameters and they are optional. Hence, a
function may or may not have parameters.
Contd...
• Function name should be unique. Rules for
naming identifiers also applies for function
naming.
• A function may or may not return a value.
• The statements outside the function
indentation are not considered as part of the
function
User defined functions can be
• Function with no argument and no return
value.
• Function with arguments but no return
value.
• Function with argument and return value.
• Function with no argument and return
value
Function with no argument and no
return value
• Function may or may not return a value.
• Non returning function is also known as
VOID function.
• These functions will always return None.
Function with no argument and no
return value
Function with no argument and no
return value
Function with arguments but no return
value
Function with argument and return
value
• We can return values from function using
return keyword.
• The return value must be used at the
calling place by
– Either store it any variable
– Use with print()
– Use in any expression
Function with argument and return
value
Function without argument and return
value
Parameters and Arguments …
• Parameters are the name(s) provided in the parenthesis when
we write function header.
• These are the values required by function to work.
• Example:
def area(radius): parameter
return(3.14*radius**2)
Arguments are the value(s) provided in function call/invoke
statement
Example :
>>> area (5) Argument
Distinguish between Actual Parameter and
Formal Parameter
Actual Parameter Formal Parameter
1.Used in function call 1.Used in function header of
statement the called function
2.Send value from calling 2.Receives value from actual
function to called function parameter
Example example
add(10,20,30) def add(x,y,z):
return (x+y+z)
Actual parameter are Formal parameter are x,y,z
Example
Programs using User defined
Functions
• 1) Write a program with a user defined
function to count the number of times a
character (passed as argument) occurs in
the given string.
Source code:
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)
Returning Multiple values
• Unlike other programming languages, python
lets you return more than one value from
function.
• The multiple return value must be either stored
in TUPLE or we can UNPACK the received
value by specifying the same number of
variables on the left of assignment of function
call.
Example
Types of arguments passed to a
function
• Positional Arguments
• Default Arguments
• Keyword Argument or named arguments.
Positional Arguments:
• These are the most common type of arguments and are matched to the
function parameters based on their positions.
• The first argument corresponds to the first parameter, the second
argument corresponds to the second parameter, and so on.
• The number and order of positional arguments must match the
function's parameter list.
Example :
def add(a,b):
return(a+b)
add(20,30)
a=20 and b=30
add(100,300)
a=100 and b=300
Default Arguments
• Sometimes we can provide default values for our positional arguments. In
this case if we are not passing any value then default values will be
considered.
• Default argument must not followed by non-default arguments.
Example
def power(base,exponent=2):
return base ** exponent
Result= power(3) #using default value
Result2=power(3,4) # providing specific
value
Keyword arguments or Named
arguments:
• In this type, each argument is preceded by a keyword
(parameter name) followed by an equal sign.
• The order of keyword arguments does not matter, as
they are matched to the function parameters based on
their names.
• These arguments provide flexibility to call a function
with arguments passed in any order.
def add(a,b,c=0):
return(a+b+c)
sum1=add(1,2)
sum2=add(a=1,b=2,c=3)
sum3=add(b=10,a=2)
print(sum1) #3
print(sum2) #6
print(sum3) #12
Example of legal/illegal function call
Scope Variables in Functions :-
• Scope Variable means accessing capability
of variable, inside the program.
• It is classified into two types :
1. Global Variables
2. Local Variables.
Global scope
• Normally All variables which will
declared under the “_main_” they are
consider Global but, all variables which
are declared under the function body they
are consider local.
Global scope example
Local scope
Global Keyword
• In Python the global keyword is used to indicate that a variable
declared inside a function should be treated as a global variable,
rather than a local variable .
• When you assign a value to a variable inside a function, Python,
by default, creates a local variable within that function’s scope.
• You need to modify a global variable from within a function,
you must use the global keyword to specify that you want to
work with the global variable instead.
• Here's the basic syntax for using the global keyword
global variable_name
Global Keyword