FUNCTIONS
A function is a block of organized, reusable code thatis
used to perform a single, relatedaction.
Functions provide better modularity for theapplications.
Functions provide a high degree of codereusing.
RULES FOR DEFINING FUNCTION IN PYTHON
Function blocks begin with the keyword def followed by the function nameand
parentheses ( ( )).
Any input parameters or arguments should be placed within these parentheses.
We also define parameters inside theseparentheses.
The code block within every function starts with a colon (:) and isindented.
The statement return [expression] exits a function, optionally passing backan
expression to thecaller.
A return statement with no arguments is the same as returnNone.
FunctionSyntax
Thekeyword
def
introduces a
function
definition.
Input Parameter is placed withinthe
parenthesis() and also define
parameter inside theparenthesis.
Return statement exits a
function block. And we canalso
use return with noargument.
The codeblock
within every
function starts
with a colon(:).
Passing arguments :-when the user defined function is called ,values are
transferred from calling function to called function.Thesevalues are
called as arguments.
1.Required arguments
2.Keyword arguments
3.Default arguments
4.Variable length arguments
PASSING ARGUMENTS
REQUIRED ARGUMENT VALUES
VALUES
Required arguments are mandatory for the function call
First the required argument should be listed,then
the default argument should be listed.
EXAMPLE:
Output:
In this code, argument ‘b’
has given a defaultvalue.
ie(b=10),and a is
required argument.
When the value of ‘b’ is notpassed
in function ,then it takes default
argument.
def sum(a,b=10):
return(a+b)
print("sum=",sum(10,20))
print("sum=",sum(20))
print("sum=",sum(10))
Sum=30
Sum=30
Sum=20
DEFAULT ARGUMENT VALUES
Default Argument-argument that assumes a default value if a value is not
provided in the function call for thatargument.
The default value is evaluated onlyonce.
EXAMPLE:
Output:
In this code, argument ‘b’
has given a defaultvalue.
ie(b=90)
When the value of ‘b’ is notpassed
in function ,then it takes default
argument.
DEFAULTARGUMENTS
Thedefaultvalueisevaluatedonlyonce.Thismakesadifferencewhenthe
defaultisamutableobjectsuchasalist,dictionary,orinstancesofmost
classes.
Example:
ifwe don’t want thedefaultvalueto be shared between subsequentcalls,
then
Example:
Output:
Output:
KEYWORDARGUMENTS
Keyword arguments are related to the functioncalls.
Using keyword arguments in a function call, the caller identifies the arguments
by the parametername.
Allows to skip arguments or place them out of order, the Python interpreter
use the keywords provided to match the values withparameters.
Example:
Output:
Caller identifies the keyword
argument by the parameter name.
Calling of the argumentOrder
doesn’t matter.
ARBITRARY ARGUMENTLISTS
Variable-LengthArguments:more arguments than we specified while defining
thefunction.
These arguments are also called variable-length arguments.
An asterisk (*) is placed before the variable name that holds the values of all non
keyword variablearguments.
This tuple remains empty if no additional arguments are specified during the
function call.
Syntax:
deffunction_name([formal_args],*var_args_tuple):
statement1……
statement2……
return[expression]
This is called
arbitrary argument
and asterisk signis
placed before the
variablename.
ARBITRARY ARGUMENTLISTS
EXAMPLE1:
Output: Output:
EXAMPLE2:
Any formal parameter which
occur after the *args
parameter arekeyword-only
arguments.
If formal parameter are not
keyword argument thenerror
occurred.
Monika
Ranbir
Purva
Lalit
def fun2(*variable,value="Monika"):
print(value)
for valin variable:
print(val)
return
fun2("Ranbir","Purva","Lalit")
LAMBDAEXPRESSIONS
Small functions can be created with the lambda keyword also knownas
Anonymousfunction.
Used wherever functions object arerequired.
These functions are called anonymous because they are not declared inthe
standard manner by using the def keyword..
Syntax:
EXAMPLE:
lambda [arg1[,arg2,.....argn]]:expression
Output:
The function returns the multiplyof
twoarguments.
Lambda function is restricted toa
singleexpressions.
Anonymous
Functions
Returning Statement
The return statement is used to return the
values from user-defined function to
calling statement.
Return keyword is used to return values
Returning values
Example Description
returnc Returns c from thefunction
return100
Returns constantfroma function
returnlst Return thelist thatcontainsvalues
returnz,y,z Returns more than onevalue
Returning M values
# A function that returnstworesults
def sum_sub(a,b):
c = a +b
d = a –b
return c,d
# get the results fromsum_sub()function
x, y = sum_sub(10,5)
# display the results
print("Result of addition: ",x)
print("Result of subtraction: ",y)
Recursive Function
A function which calls itself is called recursive function
EXAMPLE:
def pr(a):
if(a>0):
print(a)
pr(a-1)
else:
return()
pr(5)
Output
5
4
3
2
1
Local and GlobalVariables
KEY DIFFERENCE
Local variable is declared inside a function whereas Global variable is declared outside the
function.
Local variables are created when the function has started execution and is lost when the function
terminates, on the other hand, Global variable is created as execution starts and is lost when the
program ends.
Local variable doesn’t provide data sharing whereas Global variable provides data sharing.
Local variables are stored on the stack whereas the Global variable are stored on a fixed location
decided by the compiler.
Parameters passing is required for local variables whereas it is not necessary for a global variable
LOCAL VARIABLE
Local Variableis defined as a type of variable declared within programming block or
subroutines. It can only be used inside the subroutine or code block in which it is declared.
The local variable exists until the block of the function is under execution. After that, it will
be destroyed automatically.
Example of Local Variable
#local variable
deffunct():
z=10
print("local variable value",z)
funct()
print("local variable outsidevalue",z)
GLOBAL VARIABLE
A Global Variablein the program is a variable defined outside the subroutine or
function. It has a global scope means it holds its value throughout the lifetime of the
program. Hence, it can be accessed throughout the program by any function
defined within the program, unless it is shadowed.
EXAMPLE:
#global variable
z=10
def funct():
print("global variable value",z)
funct()
print("global variable outside value",z)
DIFFERENCE BETWEEN LOCAL /GLOBAL
Parameter Local Global
Scope It is declared inside a function. It is declared outside the function.
Value If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.
Lifetime
It is created when the function starts
execution and lost when the functions
terminate.
It is created before the program's global
execution starts and lost when the program
terminates.
Data sharing
Data sharing is not possible as data of the local
variable can be accessed by only one function.
Data sharing is possible as multiple functions
can access the same global variable.
Parameters
Parameters passing is required for local
variables to access the value in other function
Parameters passing is not necessary for a
global variable as it is visible throughout the
program
Modification of variable value
When the value of the local variable is
modified in one function, the changes are not
visible in another function.
When the value of the global variable is
modified in one function changes are visible in
the rest of the program.
Accessed by
Local variables can be accessed with the help
of statements, inside a function in which they
are declared.
You can access global variables by any
statement in the program.
Memory storage It is stored on the stack unless specified.
It is stored on a fixed location decided by the
compiler.
USING GLOBAL STATEMENT
It is used to declare the variable as global variables,oncethe variable is declared
as global the corresponding variable can be used in any other function
#global statement
def ff():
global m
m=10
print("m value inside function ",m)
ff()
print("m value outside function ",m)
MODULES
A module allows you to logically organize your Python code.
Grouping related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can bind and
reference.
Simply, a module is a file consisting of Python code.
A module can define functions, classes and variables. A module can also include
runnablecode.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
def greeting(name):
print("Hello, " + name)
Importing elements of a Module
Importing all elements
Importing specific elements of a module
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("John")
Built-in Modules
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a module. The dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)