You are on page 1of 22

FUNCTIONS

DEPARTMENT OF MECHANICAL ENGINEERING


DEFINITION

 A function is a block of code which is used to perform some

specific actions. A function provides higher modularity and code

reusability.

 Functions help to break a large code into smaller modules.

Syntax:

def function_name(parameters):

#Block of code or statements

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
PYTHON FUNCTIONS

 There are two kinds of functions in Python.

• Built-in functions that are provided as part of Python -

raw_input(), type(), float(), int() ...

• User Defined Functions that we define ourselves and then

use

 We treat the of the built-in function names as "new" reserved

words (i.e. we avoid them as variable names)

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
FUNCTION DEFINITION

• In Python a function is some reusable code that takes arguments(s)

as input does some computation and then returns a result or results

• We define a function using the def reserved word

• We call/invoke the function by using the function name, parenthesis

and arguments in an expression

• The block of a code of every function should begin with a colon (:)

• An optional ‘return’ statement to return a value from the function.

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
• Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior, and you need to

inform them in the same order that they were defined.


• Example:
def printme( str ):
"This prints a passed string function"
print str
return

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
CALLING A FUNCTION
• Following is the example to call printme() function:
def printme( str ): "This is a print function“
print str;
return;

printme("I'm first call to user defined function!");


printme("Again second call to the same function");

• This would produce following result:


I'm first call to user defined function!
Again second call to the same function

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
CALLING A FUNCTION USING PARAMETERS

• We can define any number of parameters while defining a function.

Syntax:
def my_function(parameters):
#Block of code or statements

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
RETURN STATEMENT

• Function can take input values as parameters and executes

business logic and returns output to the caller with return

statement

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
RETURNING MULTIPLE VALUES FROM A FUNCTION

 A function can returns a single value in the programming

languages like C, C++ and JAVA. But, in python, a function can

return multiple values.

 When a function calculates multiple results and wants to return

the results, we can use return statement as:

return a, b, c

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
EXAMPLE
def calc(a,b):

c=a+b

d=a-b

e=a*b

return c,d,e

x,y,z=calc(5,8)

print ("Addition=",x)

print ("Subtraction=",y)

print ("Multiplication=",z)

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
SCOPE AND LIFETIME OF THE VARIABLE

 The scope of a variable determines its accessibility and


availability in different portions of a program. Their availability
depends on where they are defined. Similarly, life is a period in
which the variable is stored in the memory.
 Depending on the scope and the lifetime, there are two kinds of
variables in Python.

• Local Variables - inside function , with in function

• Global Variables - outside function ,

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
LOCAL VARIABLES VS GLOBAL VARIABLES

 Variables or parameters defined inside a function are called local


variables as their scope is limited to the function only. On the contrary,
Global variables are defined outside of the function.
 Local variables can’t be used outside the function whereas a global
variable can be used throughout the program anywhere as per
requirement.
 The lifetime of a local variable ends with the termination or the
execution of a function, whereas the lifetime of a global variable ends
with the termination of the entire program.
 The variable defined inside a function can also be made global by
using the global statement.

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
PYTHON FUNCTION ARGUMENTS
 Parameters are the variables that are defined or used inside
parentheses while defining a function, whereas arguments are the
value passed for these parameters while calling a function.
Arguments are the values that are passed to the function at run-time
so that the function can do the designated task using these values

#Defining a function first to return the value of parameter


def display(x): #x is the parameter
return x
#Calling the function and supplying arguments
print ("Hello " + display('David’)) #'David' is the argument

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
TYPES OF FUNCTION ARGUMENTS IN PYTHON

A function by using the following types of actual arguments:

– Required arguments or positional

– Keyword arguments

– Default arguments

– Variable-length arguments

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
REQUIRED ARGUMENTS
 Required arguments are the arguments passed to a function in
correct positional order.

Example :

def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
KEYWORD ARGUMENTS
 In function, the values passed through arguments are assigned to
parameters in order, by their position.
 With Keyword arguments, we can use the name of the parameter
irrespective of its position while calling the function to supply the
values. All the keyword arguments must match one of the arguments
accepted by the function.

def print_name(name1, name2):


""" This function prints the name """
print (name1 + " and " + name2 + " are friends")

#calling the function


print_name(name2 = 'John',name1 = 'Gary')
D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
DEFAULT ARGUMENTS
 Sometimes we may want to use parameters in a function that takes
default values in case the user doesn’t want to provide a value for
them.
 For this, we can use default arguments which assumes a default
value if a value is not supplied as an argument while calling the
function. In parameters list, we can give default values to one or
more parameters.

def sum(a=4, b=2):


print (a+b)

sum(1,2) #calling with arguments


sum( ) #calling without arguments
D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
VARIABLE-LENGTH ARGUMENTS

 Sometimes you may need more arguments to process function then you
mentioned in the definition. If we don’t know in advance about the
arguments needed in function, we can use variable-length arguments also
called arbitrary arguments.
 For this an asterisk (*) is placed before a parameter in function definition
which can hold non-keyworded variable-length arguments and a double
asterisk (**) is placed before a parameter in function which can hold
keyworded variable-length arguments.
 If we use one asterisk (*) like *var, then all the positional arguments from
that point till the end are collected as a tuple called ‘var’ and if we use two
asterisks (**) before a variable like **var, then all the positional arguments
from that point till the end are collected as a dictionary called ‘var’.

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
def display(*name, **address):
for items in name:
print (items)

for items in address.items():


print (items)

#Calling the function


display('john','Mary','Nina',John='LA',Mary='NY',Nina='DC')

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
RECURSIVE FUNCTION
 Recursion means iteration. A function is called recursive, if the body of
function calls the function itself until the condition for recursion is true.
Thus, a Python recursive function has a termination condition.

def fact(n):
if n == 1:
return 1
else:
return (n * fact(n-1))

print ("3! = ",fact(3))

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
Advantages of Python Recursion
 Reduces unnecessary calling of function, thus reduces length of program.
 Very flexible in data structure like stacks, queues, linked list and quick sort.
 Big and complex iterative solutions are easy and simple with Python recursion.
 Algorithms can be defined recursively making it much easier to visualize and
prove.

Disadvantages of Python Recursion


 Slow.
 Logical but difficult to trace and debug.
 Requires extra storage space. For every recursive calls separate memory is
allocated for the variables.
 Recursive functions often throw a Stack Overflow Exception when processing or
operations are too large.

D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G
D E PA R T M E N T O F M E C H A N I C A L E N G I N E E R I N G

You might also like