You are on page 1of 28

\

Functions
Chapter 3
IN THIS CHAPTER
 Introduction
 Understanding Functions
 Defining Functions in Python
 Flow of Execution in a Function
Call
 Passing Parameters
 Returning Values From Functions
 Composition
 Scope of Variables
yth
p

.o.... n

Python
Functions

A Function is a subprogram that acts on


data and often returns a value.
• Functions provide better modularity for your
application and a high degree of code reusing.
• A function is a block of code which only runs
when it is called.
• You can pass data, known as parameters, into a
function.
• A function can return data as
a result. Types of funct ions:
i. Built in
ii.User Defined
yth
p

.o.... n

UNDERSTANDING
FUNCTIONS
A programmers can write their own function(s). These
functions can then be combined to form a module which
can then be used in other programs by importing them.

• To define a function keyword def is used.

• def means a function definition is starting .

• The statements indended below the function define the


functionality (working) of the function . This block is
also called body of the function .

• The return statement returns the computed value


.

You can create functions in a program


that:
 Can have arguments if needed

 Can perform certain functionality


 Can return a result
yth
p
Defining a Function
the Syntax of fun ct ion is: .o.... n
et NAME ( [PARAMETER1, PARAMETER2, ... .. ] ):
statement(s)
• In a syntax language:
• Item(s) inside angle brackets <> has to be provided by
the programmer.
• Item(s) inside square brackets [ ] is optional ,i.e., can be
omitted .
• Item(s) /words/punctuators outside < > and [ ] have to be written
as specified.
# indented (4 space) st atement

Note: The fi rst line of function definition, i.e., Line No. 1 is called
header and the rest, i.e. Line No. 2 in our example, is known as bo
dy . Consisting of sequence of indented (4 space) Python stat
# Line No. 1
ement(s), to perform a t ask.
# Line No.2

Let"s write a function to greet the world:


def sayHello ():
print "Hello World!"

SOME TERMS
• Function header : the first line begins with keyword def
and ends with a colon (:), specifies the name of function
and its parameters.
• Parameters : variables that are listed within the
parentheses of a function header.
• Indentation: the blank in the beginning of a statement
within a block.
pyth.o. ..

n
.

Flow of Execution IN A Function


Call

Inorder to ensure that a function is defined before its first use,


you have to know the order in which statements are executed,
which is called the flow of execution.
• Execution always begins at the first statement of the
program. Statements are executed one at a time, in order
from top to bottom.
• Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are
not executed unt il the function is called.
• A function call is like a going out of the flow of execution.
Instead of going to the next statement, the flow jumps to the
body of the function, executes all the statements there, and
then comes back to pick up where it left off.
AN EXECUTION FRAME CONTAINS
o Some internal information (used for debugging)
o Name of the function
o Values passed to functions
o Variables created within function
o Information about the next instruction to be executed
pyt
h.o. n
...

Flow of execution def isprime(x):


For I in range(2,x):
If x%i==0:
• Look at the program print (“number is prime “)
• First line of execution is line 8, why because Break
function will not get executed until it is called else:
through its name. print(“number is prime”)
• In Line 8 fuction isprime is called with value isprime (21)
21, isprime (22)
• After line 8, execution will start from line 1 to isprime (23)
line 7.
isprime (24)
• Then control will come to line 9.
• Here function is called 4 times and we are
reusing the code
>>>%Run ex5.py
number is not prime
number is not prime
number is prime
number is not prime
>>>
pyth.o.
..

n
.

Parameters or
ARGUMENTS

The terms parameter and argument can be


used for the same th in g: information that
are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the


parentheses in the function definition.

An argument is the value that is sent to the


function when it is called.
pyth.o.
..

n
.

Function arguments
There are various types of User-defined

functions variations based on arguments:

1. Functions without arguments

2. Functions with arguments

3. Functions with default arguments

4. Functions with multiple arguments


pyth.o.
..

n
User-defined Functions without
.

argument

>>> def evenodd( ): #no argument in


parenthesis a=int(input("enter a
number:" )
if a%2==0:
pr in t a,"is even"
else:
print a,"is odd"
'+'
>>> evenodd( )
Enter a num
ber :45 45 is
odd
yth
p
User-defined Functions
.o.... n
with argument
i'
def evenodd( a ): # with argument in
parenthesis
if a%2==0:
print( a, "is
A parameter is the variable
even")
listed inside the parentheses
else: in the function definition.
print( a, "is odd")
a=int(input("enter a
evenodd(
number:" )a )
t
An argument is the value that is sent
to the function when it is called.

Out put :
Enter a number:45
45 is odd
PASSING PARAMETERS
Python supports three types of formal arguments / parameters:
1. Positional arguments (required arguments
2. Default arguments
3. Keywords (or named ) arguments

Positional /Required Arguments


When the function call statement must match the number and
order of arguments as defined in the function definition ,this is
called the positional argument matching.

• The arguments must be provided for all parameters (required)


• The values of arguments are matched with parameters
,position (order)wise (positional)

This way of parameter and argument specification is called


Positional arguments or Required arguments or Mandatory
arguments as no value can be skipped from the function call or you
cannot change the order

Default Arguments
A parameter having default value in the function header is
known as a default parameter.
Non default arguments cannot follow default argument .
User-defined Functions with default argument
A default argument is an argument that assumes a default value if a
value is not provided in the function call for that argument. The
following example gives an idea on default arguments

def evenodd( a=2 ): # with default argument in


parenthesis
if a0/4,2 ==0
print( a."1s even")
f"lse
prin t( a."is odd" )
evenodd( ) # no argument but still getting a·s value
evenodd( 20 )
evenodd( 21 )
I

icfl AST
Exception
.
Transfer of value from argument to parameter
with keywords
#order of argument can be change by
mentioning parameter's name = argument for
all arguments
Functions with Variable-
length arguments
You may need to process a fun ct ion for more
arguments than you specified while defining
the funct ion. These arguments are
called variable-lengt h argument s and are not
named in the funct ion defi nit ion, unlike
required and default arguments.
Syntax
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite return
[expression]

An asterisk(*) is placed before the variable name that


holds the values of all non keyword variable argument s.
This t upl e remains empty if no additional arguments are
specifi ed during the funct ion call. Following is a simple
example -
.

Function return
statement
There are various types of User-defined

functions variations based on return

statements:
1. Functions without return statement

2. Functions with return statement

3. Functions with multiple return values


.
Functions with return
statement

The statement return [expression] exits a function,


optionally passing back an expression to the caller. A
return statement with no arguments is the same as
return None.

>>> def evenodd(a):


if a%2==0:
return"
even" else:
return "
odd"

>>>
x=evenodd(34)
>>> print
x even
Scope of a variables
Variables can only reach the area in which they are
defined, which is called scope.
Think of it as the area of code where variables can be
used.
There are two types of variable scopes :
->L, pe
L ocal Scope

Python supp ort s globa l variables (usable in the entire


program) and locavl ariables. By default , all variables de
clared in a
funct ion are local variables.
pyth.o.
..

Global Scope n
.

With global scope, variable can be used anywhere in the


program

eg:
X=50
V I . \ J ... ( ) •.
1 ns1de test x is ", x)

print("value of x is ", x)

Output:
inside test x is 50
value of x is 50
pyth.o.
..

Local Scope n
.

With local scope, variable can be used only within the


function / block that it is created
Eg:
X=50
( ):
y 20
a ue of x is ', X, ' y is '

v\

print('value of x is ', X, ' y is ' , y)


On executing the code we will
The
get next
Valueprint
of x statement will produce an error, because
is 50 y is 20
the variable y is not accessible outside the def()
pyth.o.
..

More on Scope of Variables n


.

To access global variable inside the function prefix


keyword global with the variable
Eg:

X=50
de f test ( ):
global x =5
y=2
print('value of x & y inside the function are ' , x , y)
Print('value of x outside function is ' ', x' )

This code will produce following output:


Value of x & y inside the function are 5
2 Value of x outside the function is 5
,- pyth
-- on
Using main() as a Function ·.......--
What is the main() function in Python?
Some programming languages have a special function called main() which
is the execution point for a program file. Python interpreter, however,
runs
each line serially from the top of the file and has no explicit main()
function.

Python offers other conventions to define the execution point. One of


them is using the main() function and the _ n a m e _ property of a
python file.
The _ n a m e _ variable is a special builtin Python variable that shows
the name of the current module.
It has different values depending on where we execute the Python file.

def main():
print ("Hello
World") if _ name_ =="_
main_ ":
main()
Questions on Functions yth
p
Q l . Write a program to find a given number is prime
or not using functions. .o.... n

>>> def evenodd(a):


lf a%2==0:
print a,"is even"
else:I
print a,"is odd"

>>> evenodd(45)
45 is odd
>>> evenodd(66)
66 is even
pyth.o.
Questions on Functions ..

n
.
Q2. Write a program to find whether a given number
is even or odd using functions.
>>> def prime(a):
f=O
i in range(l,a):
ror if (a%i == O):
f=f
+l if ( f>
l) :
print a," is not prime number"
else:
print a," is prime number"

>>> prime(2)
2 is prime number
>>> prime(4)
pyth.o.
Questions on ..

n
Functions
Q3. Write a program to find factors of a given
.

number using functions.

>>> e prime(a):
print " factors
are :", for i in
range(l,a+l):
if(a%i==0):
print i,

>>> prime(lO)
factors are : 1 2 5 10
.

Questions on
Functions
QS. Write a Python function to find the Max of
three numbers.
def max_of_tw(o x, y ):
f X y:
retJ x
return y
def max_of_1e( x, y, z ):
retu max_of_two( x, max_of_two(
y, max_of_three(3,
prin z ) ) 6,
-5))
.

Questions on Functions

QG. Write a Python function to


sum all the numbers in a Iist.

def s m( numbers):
total 0
for x in numbers:
total
+= x
return
total
print(sum(
(8, 2, 3, 0,
7)))
.

Questions on Functions
Q7. Write a Python program to
reverse a st rin g.

def string_rever(strl):
rstrl = ' '
index len( strl) wh
index > 0:
rstrl += strl[ index - 1 ]
index index 1
etu rstrl
pri1t(string_rever(s'e123a4bcd'))

You might also like