SlideShare a Scribd company logo
FUNCTIONS
A function is a block of organized, reusable code that is
used to perform a single, related action.
 Functions provide better modularity for the applications.
 Functions provide a high degree of code reusing.
RULES FOR DEFINING FUNCTION IN PYTHON
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses.
We also define parameters inside these parentheses.
 The code block within every function starts with a colon (:) and is indented.
 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.
Function Syntax
The keyword
def
introduces a
function
definition.
Input Parameter is placed within the
parenthesis() and also define
parameter inside the parenthesis.
Return statement exits a
function block. And we can also
use return with no argument.
The code block
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.These values 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 default value.
ie(b=10),and a is
required argument.
When the value of ‘b’ is not passed
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 that argument.
 The default value is evaluated only once.
 EXAMPLE:
Output:
In this code, argument ‘b’
has given a default value.
ie(b=90)
When the value of ‘b’ is not passed
in function ,then it takes default
argument.
DEFAULT ARGUMENTS
 The default value is evaluated only once. This makes a difference when the
default is a mutable object such as a list, dictionary, or instances of most
classes.
 Example:
 if we don’t want the default value to be shared between subsequent calls,
then
 Example :
Output:
Output:
KEYWORD ARGUMENTS
 Keyword arguments are related to the function calls.
 Using keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
 Allows to skip arguments or place them out of order, the Python interpreter
use the keywords provided to match the values with parameters.
 Example:
Output:
 Caller identifies the keyword
argument by the parameter name.
 Calling of the argument Order
doesn’t matter .
KEYWORD ARGUMENTS
 Example 1:
Output:
Example 2: Output:
ARBITRARY ARGUMENT LISTS
 Variable-Length Arguments: more arguments than we specified while defining
the function.
 These arguments are also called variable-length arguments .
 An asterisk (*) is placed before the variable name that holds the values of all non
keyword variable arguments.
 This tuple remains empty if no additional arguments are specified during the
function call.
 Syntax :
def function_name([formal_args], *var_args_tuple ):
statement 1……
statement 2……
return [expression]
This is called
arbitrary argument
and asterisk sign is
placed before the
variable name.
ARBITRARY ARGUMENT LISTS
 EXAMPLE 1:
Output: Output:
 EXAMPLE 2:
 Any formal parameter which
occur after the *args
parameter are keyword-only
arguments.
 If formal parameter are not
keyword argument then error
occurred.
Monika
Ranbir
Purva
Lalit
def fun2(*variable,value="Monika"):
print(value)
for val in variable:
print(val)
return
fun2("Ranbir","Purva","Lalit")
LAMBDA EXPRESSIONS
 Small functions can be created with the lambda keyword also known as
Anonymous function.
 Used wherever functions object are required.
 These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. .
 Syntax :
 EXAMPLE:
lambda [arg1 [,arg2,.....argn]]:expression
Output:
 The function returns the multiply of
two arguments.
 Lambda function is restricted to a
single expressions.
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
return c Returns c from the function
return 100 Returns constant from a function
return lst Return thelist that contains values
return z,y,z Returns more than one value
Returning M values
# A function that returns two results
def sum_sub(a, b):
c = a + b
d = a – b
return c, d
# get the results from sum_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 Global Variables
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 Variable is 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
def funct():
z=10
print("local variable value",z)
funct()
print("local variable outside value",z)
GLOBAL VARIABLE
A Global Variable in 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,once the 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
runnable code.
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)

More Related Content

Similar to functions notes.pdf python functions and opp

Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuplesMalligaarjunanN
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...Osama Ghandour Geris
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdfNehaSpillai1
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
 
C programming language working with functions 1
C programming language working with functions 1C programming language working with functions 1
C programming language working with functions 1Jeevan Raj
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
 

Similar to functions notes.pdf python functions and opp (20)

Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
4. function
4. function4. function
4. function
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
functions in python By Eng. Osama Ghandour الدوال فى البايثون مع مهندس اسامه ...
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
C functions
C functionsC functions
C functions
 
FUNCTIONS.pptx
FUNCTIONS.pptxFUNCTIONS.pptx
FUNCTIONS.pptx
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
C programming language working with functions 1
C programming language working with functions 1C programming language working with functions 1
C programming language working with functions 1
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
Functions in c
Functions in cFunctions in c
Functions in c
 

Recently uploaded

134. Reviewer Certificate in Computer Science
134. Reviewer Certificate in Computer Science134. Reviewer Certificate in Computer Science
134. Reviewer Certificate in Computer ScienceManu Mitra
 
0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdf
0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdf0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdf
0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdfThomas GIRARD BDes
 
Day care leadership document it helps to a person who needs caring children
Day care leadership document it helps to a person who needs caring childrenDay care leadership document it helps to a person who needs caring children
Day care leadership document it helps to a person who needs caring childrenMeleseWolde3
 
欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】
欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】
欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】foismail170
 
Employee Background Verification Service in Bangladesh
Employee Background Verification Service in BangladeshEmployee Background Verification Service in Bangladesh
Employee Background Verification Service in BangladeshSabuj Ahmed
 
133. Reviewer Certificate in Advances in Research
133. Reviewer Certificate in Advances in Research133. Reviewer Certificate in Advances in Research
133. Reviewer Certificate in Advances in ResearchManu Mitra
 
Heidi Livengood Resume Senior Technical Recruiter / HR Generalist
Heidi Livengood Resume Senior Technical Recruiter / HR GeneralistHeidi Livengood Resume Senior Technical Recruiter / HR Generalist
Heidi Livengood Resume Senior Technical Recruiter / HR GeneralistHeidiLivengood
 
Genaihelloallstudyjamheregetstartedwithai
GenaihelloallstudyjamheregetstartedwithaiGenaihelloallstudyjamheregetstartedwithai
Genaihelloallstudyjamheregetstartedwithaijoceko6768
 
0524.priorspeakingengagementslist-01.pdf
0524.priorspeakingengagementslist-01.pdf0524.priorspeakingengagementslist-01.pdf
0524.priorspeakingengagementslist-01.pdfThomas GIRARD BDes
 
0524.THOMASGIRARD_CURRICULUMVITAE-01.pdf
0524.THOMASGIRARD_CURRICULUMVITAE-01.pdf0524.THOMASGIRARD_CURRICULUMVITAE-01.pdf
0524.THOMASGIRARD_CURRICULUMVITAE-01.pdfThomas GIRARD BDes
 
129. Reviewer Certificate in BioNature [2024]
129. Reviewer Certificate in BioNature [2024]129. Reviewer Certificate in BioNature [2024]
129. Reviewer Certificate in BioNature [2024]Manu Mitra
 
132. Acta Scientific Pharmaceutical Sciences
132. Acta Scientific Pharmaceutical Sciences132. Acta Scientific Pharmaceutical Sciences
132. Acta Scientific Pharmaceutical SciencesManu Mitra
 
D.El.Ed. College List -Session 2024-26.pdf
D.El.Ed. College List -Session 2024-26.pdfD.El.Ed. College List -Session 2024-26.pdf
D.El.Ed. College List -Session 2024-26.pdfbipedoy339
 
Widal Agglutination Test: A rapid serological diagnosis of typhoid fever
Widal Agglutination Test: A rapid serological diagnosis of typhoid feverWidal Agglutination Test: A rapid serological diagnosis of typhoid fever
Widal Agglutination Test: A rapid serological diagnosis of typhoid fevertaexnic
 
欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】
欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】
欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】foismail170
 
太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】
太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】
太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】foismail170
 
Dr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdf
Dr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdfDr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdf
Dr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdfDr. Nazrul Islam
 
Master SEO in 2024 The Complete Beginner's Guide
Master SEO in 2024 The Complete Beginner's GuideMaster SEO in 2024 The Complete Beginner's Guide
Master SEO in 2024 The Complete Beginner's GuideTechEasifyInfotech
 
Part 1.pptx Part 1.pptx Part 1.pptx Part 1.pptx
Part 1.pptx Part 1.pptx Part 1.pptx Part 1.pptxPart 1.pptx Part 1.pptx Part 1.pptx Part 1.pptx
Part 1.pptx Part 1.pptx Part 1.pptx Part 1.pptxSheldon Byron
 
135. Reviewer Certificate in Journal of Engineering
135. Reviewer Certificate in Journal of Engineering135. Reviewer Certificate in Journal of Engineering
135. Reviewer Certificate in Journal of EngineeringManu Mitra
 

Recently uploaded (20)

134. Reviewer Certificate in Computer Science
134. Reviewer Certificate in Computer Science134. Reviewer Certificate in Computer Science
134. Reviewer Certificate in Computer Science
 
0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdf
0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdf0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdf
0524.THOMASGIRARD_SINGLEPAGERESUME-01.pdf
 
Day care leadership document it helps to a person who needs caring children
Day care leadership document it helps to a person who needs caring childrenDay care leadership document it helps to a person who needs caring children
Day care leadership document it helps to a person who needs caring children
 
欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】
欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】
欧洲杯投注网站-欧洲杯投注网站推荐-欧洲杯投注网站| 立即访问【ac123.net】
 
Employee Background Verification Service in Bangladesh
Employee Background Verification Service in BangladeshEmployee Background Verification Service in Bangladesh
Employee Background Verification Service in Bangladesh
 
133. Reviewer Certificate in Advances in Research
133. Reviewer Certificate in Advances in Research133. Reviewer Certificate in Advances in Research
133. Reviewer Certificate in Advances in Research
 
Heidi Livengood Resume Senior Technical Recruiter / HR Generalist
Heidi Livengood Resume Senior Technical Recruiter / HR GeneralistHeidi Livengood Resume Senior Technical Recruiter / HR Generalist
Heidi Livengood Resume Senior Technical Recruiter / HR Generalist
 
Genaihelloallstudyjamheregetstartedwithai
GenaihelloallstudyjamheregetstartedwithaiGenaihelloallstudyjamheregetstartedwithai
Genaihelloallstudyjamheregetstartedwithai
 
0524.priorspeakingengagementslist-01.pdf
0524.priorspeakingengagementslist-01.pdf0524.priorspeakingengagementslist-01.pdf
0524.priorspeakingengagementslist-01.pdf
 
0524.THOMASGIRARD_CURRICULUMVITAE-01.pdf
0524.THOMASGIRARD_CURRICULUMVITAE-01.pdf0524.THOMASGIRARD_CURRICULUMVITAE-01.pdf
0524.THOMASGIRARD_CURRICULUMVITAE-01.pdf
 
129. Reviewer Certificate in BioNature [2024]
129. Reviewer Certificate in BioNature [2024]129. Reviewer Certificate in BioNature [2024]
129. Reviewer Certificate in BioNature [2024]
 
132. Acta Scientific Pharmaceutical Sciences
132. Acta Scientific Pharmaceutical Sciences132. Acta Scientific Pharmaceutical Sciences
132. Acta Scientific Pharmaceutical Sciences
 
D.El.Ed. College List -Session 2024-26.pdf
D.El.Ed. College List -Session 2024-26.pdfD.El.Ed. College List -Session 2024-26.pdf
D.El.Ed. College List -Session 2024-26.pdf
 
Widal Agglutination Test: A rapid serological diagnosis of typhoid fever
Widal Agglutination Test: A rapid serological diagnosis of typhoid feverWidal Agglutination Test: A rapid serological diagnosis of typhoid fever
Widal Agglutination Test: A rapid serological diagnosis of typhoid fever
 
欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】
欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】
欧洲杯买球平台-欧洲杯买球平台推荐-欧洲杯买球平台| 立即访问【ac123.net】
 
太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】
太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】
太阳城娱乐-太阳城娱乐推荐-太阳城娱乐官方网站| 立即访问【ac123.net】
 
Dr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdf
Dr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdfDr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdf
Dr. Nazrul Islam, Northern University Bangladesh - CV (29.5.2024).pdf
 
Master SEO in 2024 The Complete Beginner's Guide
Master SEO in 2024 The Complete Beginner's GuideMaster SEO in 2024 The Complete Beginner's Guide
Master SEO in 2024 The Complete Beginner's Guide
 
Part 1.pptx Part 1.pptx Part 1.pptx Part 1.pptx
Part 1.pptx Part 1.pptx Part 1.pptx Part 1.pptxPart 1.pptx Part 1.pptx Part 1.pptx Part 1.pptx
Part 1.pptx Part 1.pptx Part 1.pptx Part 1.pptx
 
135. Reviewer Certificate in Journal of Engineering
135. Reviewer Certificate in Journal of Engineering135. Reviewer Certificate in Journal of Engineering
135. Reviewer Certificate in Journal of Engineering
 

functions notes.pdf python functions and opp

  • 1.
  • 2. FUNCTIONS A function is a block of organized, reusable code that is used to perform a single, related action.  Functions provide better modularity for the applications.  Functions provide a high degree of code reusing.
  • 3. RULES FOR DEFINING FUNCTION IN PYTHON  Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).  Any input parameters or arguments should be placed within these parentheses. We also define parameters inside these parentheses.  The code block within every function starts with a colon (:) and is indented.  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.
  • 4. Function Syntax The keyword def introduces a function definition. Input Parameter is placed within the parenthesis() and also define parameter inside the parenthesis. Return statement exits a function block. And we can also use return with no argument. The code block within every function starts with a colon(:) .
  • 5.
  • 6. Passing arguments :-when the user defined function is called ,values are transferred from calling function to called function.These values are called as arguments. 1. Required arguments 2. Keyword arguments 3. Default arguments 4. Variable length arguments PASSING ARGUMENTS
  • 7. 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 default value. ie(b=10),and a is required argument. When the value of ‘b’ is not passed 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
  • 8. DEFAULT ARGUMENT VALUES  Default Argument- argument that assumes a default value if a value is not provided in the function call for that argument.  The default value is evaluated only once.  EXAMPLE: Output: In this code, argument ‘b’ has given a default value. ie(b=90) When the value of ‘b’ is not passed in function ,then it takes default argument.
  • 9. DEFAULT ARGUMENTS  The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.  Example:  if we don’t want the default value to be shared between subsequent calls, then  Example : Output: Output:
  • 10. KEYWORD ARGUMENTS  Keyword arguments are related to the function calls.  Using keyword arguments in a function call, the caller identifies the arguments by the parameter name.  Allows to skip arguments or place them out of order, the Python interpreter use the keywords provided to match the values with parameters.  Example: Output:  Caller identifies the keyword argument by the parameter name.  Calling of the argument Order doesn’t matter .
  • 11. KEYWORD ARGUMENTS  Example 1: Output: Example 2: Output:
  • 12. ARBITRARY ARGUMENT LISTS  Variable-Length Arguments: more arguments than we specified while defining the function.  These arguments are also called variable-length arguments .  An asterisk (*) is placed before the variable name that holds the values of all non keyword variable arguments.  This tuple remains empty if no additional arguments are specified during the function call.  Syntax : def function_name([formal_args], *var_args_tuple ): statement 1…… statement 2…… return [expression] This is called arbitrary argument and asterisk sign is placed before the variable name.
  • 13. ARBITRARY ARGUMENT LISTS  EXAMPLE 1: Output: Output:  EXAMPLE 2:  Any formal parameter which occur after the *args parameter are keyword-only arguments.  If formal parameter are not keyword argument then error occurred. Monika Ranbir Purva Lalit def fun2(*variable,value="Monika"): print(value) for val in variable: print(val) return fun2("Ranbir","Purva","Lalit")
  • 14. LAMBDA EXPRESSIONS  Small functions can be created with the lambda keyword also known as Anonymous function.  Used wherever functions object are required.  These functions are called anonymous because they are not declared in the standard manner by using the def keyword. .  Syntax :  EXAMPLE: lambda [arg1 [,arg2,.....argn]]:expression Output:  The function returns the multiply of two arguments.  Lambda function is restricted to a single expressions. Anonymous Functions
  • 15. 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
  • 16. Returning values Example Description return c Returns c from the function return 100 Returns constant from a function return lst Return thelist that contains values return z,y,z Returns more than one value
  • 17. Returning M values # A function that returns two results def sum_sub(a, b): c = a + b d = a – b return c, d # get the results from sum_sub() function x, y = sum_sub(10, 5) # display the results print("Result of addition: ", x) print("Result of subtraction: ", y)
  • 18. 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
  • 19. Local and Global Variables 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
  • 20. LOCAL VARIABLE Local Variable is 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 def funct(): z=10 print("local variable value",z) funct() print("local variable outside value",z)
  • 21. GLOBAL VARIABLE A Global Variable in 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)
  • 22. 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.
  • 23. USING GLOBAL STATEMENT It is used to declare the variable as global variables,once the 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)
  • 24. 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 runnable code.
  • 25. 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)
  • 26. 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")
  • 27. 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)