SlideShare a Scribd company logo
Computer Science
Chapter-1
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
As Per CBSE
Syllabus
2022-23
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
A Function is a set of codes that are design to perform a single or related task,
it provide modularity and increase code reusability. A function executes only
when t is being called. Python provides many build in function like print(),
len(), type()..etc, whereas the functions created by us, is called User Defined
Functions.
When a function is called for execution, Data can be passes to the function
called as function parameters. After execution the function may return data
from the function.
What is a Function?
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Benefits of using Function
• Code Reusability: A function once created can be called countless number of times.
• Modularity: Functions helps to divide the entire code of the program into separate
blocks, where each block is assigned with a specific task.
• Understandability: use of Functions makes the program more structured and
understandable by dividing the large set of codes into functions
• Procedural Abstraction: once a function is created the programmer doesn’t have to know
the coding part inside the functions, Only by knowing how to invoke the function, the
programmer can use the function.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Types of Functions in Python
1. Built-in Function: Ready to use functions which are already defined in python and the
programmer can use them whenever required are called as Built-in functions. Ex: len(), print(),
type()..etc
2. Functions defined in Modules: The functions which are defined inside python
modules are Functions defined in modules. In order to use these functions the programmer
need to import the module into the program then functions defined in the module can be
used.
import math
math.pow(5,2)
To use the function pow(), first
we need to import the module
math, because pow() is #defined
inside the math module.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
3.User Defined Function
Functions that are defined by the programmer to perform a specific task is called as User
Defined Functions. The keyword def is used to define/create a function in python.
Defining a Function
Syntax:
Lets define our first user defined function:
def <Function Name>([parameters]):
body of the function
[statements]
def myFirstFunction ( a ):
print(“inside my first function”)
print(a)
myFirstFunction(“bye”)
Output:
Inside my first function
bye
Function Name
Function Argument
Function call
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Elements in Function Definition
• Function Header: The first line of the function definition is called as function header. The header start
with the keyword def, and it also specifies function name and function parameters. The header ends
with colon ( : ). def sum(a,b): #function Header
• Parameter: Variables that are mentioned inside parenthesis ( ) of the function Header.
• Function Body: The set of all statements/indented-statements beneath the function header that
perform the task for which the function is designed for.
• Indentation: All the statements inside the function body starts with blank space (convention is four
statements).
• Return statement: A function may have a return statement that is used to returning values from
functions. A return statement can also be used without any value or expression.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Flow of Execution in a Function Call
#Function Definition
def myfun(x,y):
.
.
return
.
.
a=10
b=20
#function call
myfun(a,b)
print(…)
When a function is called the
programs control flow will
shift to the function
definition
After the last statement of the
function is executed or when a
return statement is encountered
the control flow will shift back to
the place from where the function
is called
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Arguments and parameters in Function
In Python, the variables mentioned withing parathesis () of a function definition are
referred as parameters(also as formal parameter/formal argument) and the variables
present inside parathesis of a function call is referred as arguments (also as actual
parameter/actual argument).
Python supports 4 types of parameters/formal arguments
1. Positional Argument
2. Default Argument
3. Keyword Argument
4. Variable length argument
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
1.Positional Arguments:
When function call statement must contain the same number and order of arguments as
defined in the function definition, then the arguments are referred as positional argument.
def myfun(x,y,z):
[statements]
….
myfun(a,b,c)
myfun(a,8,9)
myfun(a,b)
# 3 values(all variables) are passed to the function as arguments
# 3 values(1 variables and 2 literals) are passed to the function as arguments
# Error: missing 1 required positional argument: `z’
Positional arguments are required arguments or
mandatory arguments as no value can be skipped
from function call or you cant change the order of
the argument passing.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
2.Default Argument
Default values can be assigned to parameter in function header while defining a function,
these default values will be used if the function call doesn’t have matching arguments as
function definition.
def findresult (mark_secured, passing_mark=30):
if mark_secured>= passing mark:
print(“pass”)
else:
print(“fail”)
findresult(46,40)
findresult(52)
Output:
pass
pass *Note: non-default arguments cannot follow default arguments
Here the argument
passing_mark has assigned
with a default value, the
default value can only be
used if the function call
doesn’t have matching
arguments
for this function call default value will not be used as call have matching arguments, hence
the value 46 is assigned to mark_secured and 40 assigned to passing_mark.
for this function call default value will be used as function call doesn’t have matching
arguments as function definition, hence the value 52 is assigned to mark_secured and the
default value 30 is assigned to passing_mark.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Keyword Argument
Python allows to call a function by passing the in any order, in this case the programmer
have to spcify the names of the arguments in function call.
def findpow(base, exponent):
print(base**exponent)
findpow(5,2)
findpow(exponent=5,base=2)
Output:
25
32
Keyword Arguments
In the 2nd function call base gets the value 2 and
exponent is assigned with the value 5
In the 1st function call base gets the value 5 and
exponent is assigned with the value 2
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Variable Length Argument
Variable Length Argument in python permits to pass multiple values to a single parameter.
The variable length argument precedes the symbol ‘*’ in the function header of the
function call.
def findsum(*x):
sum=0
for i in x:
sum=sum+i
print(“sum of numbers is: ’’, sum)
findsum(6,2,8,5,2)
findpow(34,2,4,10,22,14,6)
Output:
sum of numbers is: 23
sum of numbers is: 92
Variable Length Arguments
The function parameter x can hold any number of vaues
passed in function call to this function, here the
parameter x behaves like a tuple.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Returning Values from Function
Functions in python can return back values/variables from the function to the place from
where the function is called using return statement. Function may or may not return values,
python function can also return multiple values.
return statement terminates the function execution if it is encountered.
def sayhello(name):
message=”hello “+ name
return message
m=sayhello(“amit”)
print(m)
Output:
hello amit
Function returns a single value back to the place from
where function was called.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Scope of Variables
Part(s) of the program where the variable is legal and accessible is referred as its scope.
Based on scope, variable are categorized into 2 categories
Local Variable-: Variable defined inside a function is called as Local Variable. Its scope is
limited only within the function in which it is defined.
Global Variable: Variable defined outside all function is called as Global variable.
def findsum(a,b):
c=a+b
return c
x,y=10,20
m=findsum(x,y)
print(m)
Output:
30
Here the variable a, b and c is defined
inside the function, so a, b and c is
Local variables.
The variable x, y and m is are not
defined inside any function, so x, y and
m is Global variables.
K V C o d e r s
L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E
Using a Global variable in local scope
To access a variable declared outside all functions(Global Variable) in a local scope then
global statement is used.
When global statement is used for a name, it restrict the function to create a local variable
of that name instead the function uses the global variable.
a=10
def add(x):
a=x+5
print(x)
add(20)
print(a)
Output:
25
10
a=10
def add(x):
global a
a=x+5
print(x)
add(20)
print(a)
Output:
25
25
Inside the function a local variable with name a is
created, so changes to the value of local variable a,
doesn’t affect the value of the global variable a.
Use of the global statement restrict the
function to create a local variable with
name a, instead the function is accessing
the global variable a. So any changes made
to a inside the function will affect the value
of global variable a.

More Related Content

Similar to functionfunctionfunctionfunctionfunction12.pdf (20)

Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
JuanPicasso7
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
Userdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdf
DeeptiMalhotra19
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjw
MayankSinghRawat6
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Python functions
Python functionsPython functions
Python functions
ToniyaP1
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
Python_Functions_Modules_ User define Functions-
Python_Functions_Modules_ User define Functions-Python_Functions_Modules_ User define Functions-
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
functions new.pptx
functions new.pptxfunctions new.pptx
functions new.pptx
bhuvanalakshmik2
 
Function in Python function in python.pptx
Function in Python function in python.pptxFunction in Python function in python.pptx
Function in Python function in python.pptx
JHILIPASAYAT
 
_Python_ Functions _and_ Libraries_.pptx
_Python_ Functions _and_ Libraries_.pptx_Python_ Functions _and_ Libraries_.pptx
_Python_ Functions _and_ Libraries_.pptx
yaramahsoob
 
Notes5
Notes5Notes5
Notes5
hccit
 
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
RutviBaraiya
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
JuanPicasso7
 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
 
Userdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdf
DeeptiMalhotra19
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjw
MayankSinghRawat6
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Python functions
Python functionsPython functions
Python functions
ToniyaP1
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
Python_Functions_Modules_ User define Functions-
Python_Functions_Modules_ User define Functions-Python_Functions_Modules_ User define Functions-
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
Function in Python function in python.pptx
Function in Python function in python.pptxFunction in Python function in python.pptx
Function in Python function in python.pptx
JHILIPASAYAT
 
_Python_ Functions _and_ Libraries_.pptx
_Python_ Functions _and_ Libraries_.pptx_Python_ Functions _and_ Libraries_.pptx
_Python_ Functions _and_ Libraries_.pptx
yaramahsoob
 
Notes5
Notes5Notes5
Notes5
hccit
 
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
Unit_2.0_Functions (1).pdfUnit_2.0_Functions (1).pdf
RutviBaraiya
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 

Recently uploaded (20)

How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Ad

functionfunctionfunctionfunctionfunction12.pdf

  • 1. Computer Science Chapter-1 K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E As Per CBSE Syllabus 2022-23
  • 2. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E A Function is a set of codes that are design to perform a single or related task, it provide modularity and increase code reusability. A function executes only when t is being called. Python provides many build in function like print(), len(), type()..etc, whereas the functions created by us, is called User Defined Functions. When a function is called for execution, Data can be passes to the function called as function parameters. After execution the function may return data from the function. What is a Function?
  • 3. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Benefits of using Function • Code Reusability: A function once created can be called countless number of times. • Modularity: Functions helps to divide the entire code of the program into separate blocks, where each block is assigned with a specific task. • Understandability: use of Functions makes the program more structured and understandable by dividing the large set of codes into functions • Procedural Abstraction: once a function is created the programmer doesn’t have to know the coding part inside the functions, Only by knowing how to invoke the function, the programmer can use the function.
  • 4. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Types of Functions in Python 1. Built-in Function: Ready to use functions which are already defined in python and the programmer can use them whenever required are called as Built-in functions. Ex: len(), print(), type()..etc 2. Functions defined in Modules: The functions which are defined inside python modules are Functions defined in modules. In order to use these functions the programmer need to import the module into the program then functions defined in the module can be used. import math math.pow(5,2) To use the function pow(), first we need to import the module math, because pow() is #defined inside the math module.
  • 5. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E 3.User Defined Function Functions that are defined by the programmer to perform a specific task is called as User Defined Functions. The keyword def is used to define/create a function in python. Defining a Function Syntax: Lets define our first user defined function: def <Function Name>([parameters]): body of the function [statements] def myFirstFunction ( a ): print(“inside my first function”) print(a) myFirstFunction(“bye”) Output: Inside my first function bye Function Name Function Argument Function call
  • 6. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Elements in Function Definition • Function Header: The first line of the function definition is called as function header. The header start with the keyword def, and it also specifies function name and function parameters. The header ends with colon ( : ). def sum(a,b): #function Header • Parameter: Variables that are mentioned inside parenthesis ( ) of the function Header. • Function Body: The set of all statements/indented-statements beneath the function header that perform the task for which the function is designed for. • Indentation: All the statements inside the function body starts with blank space (convention is four statements). • Return statement: A function may have a return statement that is used to returning values from functions. A return statement can also be used without any value or expression.
  • 7. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Flow of Execution in a Function Call #Function Definition def myfun(x,y): . . return . . a=10 b=20 #function call myfun(a,b) print(…) When a function is called the programs control flow will shift to the function definition After the last statement of the function is executed or when a return statement is encountered the control flow will shift back to the place from where the function is called
  • 8. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Arguments and parameters in Function In Python, the variables mentioned withing parathesis () of a function definition are referred as parameters(also as formal parameter/formal argument) and the variables present inside parathesis of a function call is referred as arguments (also as actual parameter/actual argument). Python supports 4 types of parameters/formal arguments 1. Positional Argument 2. Default Argument 3. Keyword Argument 4. Variable length argument
  • 9. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E 1.Positional Arguments: When function call statement must contain the same number and order of arguments as defined in the function definition, then the arguments are referred as positional argument. def myfun(x,y,z): [statements] …. myfun(a,b,c) myfun(a,8,9) myfun(a,b) # 3 values(all variables) are passed to the function as arguments # 3 values(1 variables and 2 literals) are passed to the function as arguments # Error: missing 1 required positional argument: `z’ Positional arguments are required arguments or mandatory arguments as no value can be skipped from function call or you cant change the order of the argument passing.
  • 10. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E 2.Default Argument Default values can be assigned to parameter in function header while defining a function, these default values will be used if the function call doesn’t have matching arguments as function definition. def findresult (mark_secured, passing_mark=30): if mark_secured>= passing mark: print(“pass”) else: print(“fail”) findresult(46,40) findresult(52) Output: pass pass *Note: non-default arguments cannot follow default arguments Here the argument passing_mark has assigned with a default value, the default value can only be used if the function call doesn’t have matching arguments for this function call default value will not be used as call have matching arguments, hence the value 46 is assigned to mark_secured and 40 assigned to passing_mark. for this function call default value will be used as function call doesn’t have matching arguments as function definition, hence the value 52 is assigned to mark_secured and the default value 30 is assigned to passing_mark.
  • 11. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Keyword Argument Python allows to call a function by passing the in any order, in this case the programmer have to spcify the names of the arguments in function call. def findpow(base, exponent): print(base**exponent) findpow(5,2) findpow(exponent=5,base=2) Output: 25 32 Keyword Arguments In the 2nd function call base gets the value 2 and exponent is assigned with the value 5 In the 1st function call base gets the value 5 and exponent is assigned with the value 2
  • 12. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Variable Length Argument Variable Length Argument in python permits to pass multiple values to a single parameter. The variable length argument precedes the symbol ‘*’ in the function header of the function call. def findsum(*x): sum=0 for i in x: sum=sum+i print(“sum of numbers is: ’’, sum) findsum(6,2,8,5,2) findpow(34,2,4,10,22,14,6) Output: sum of numbers is: 23 sum of numbers is: 92 Variable Length Arguments The function parameter x can hold any number of vaues passed in function call to this function, here the parameter x behaves like a tuple.
  • 13. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Returning Values from Function Functions in python can return back values/variables from the function to the place from where the function is called using return statement. Function may or may not return values, python function can also return multiple values. return statement terminates the function execution if it is encountered. def sayhello(name): message=”hello “+ name return message m=sayhello(“amit”) print(m) Output: hello amit Function returns a single value back to the place from where function was called.
  • 14. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Scope of Variables Part(s) of the program where the variable is legal and accessible is referred as its scope. Based on scope, variable are categorized into 2 categories Local Variable-: Variable defined inside a function is called as Local Variable. Its scope is limited only within the function in which it is defined. Global Variable: Variable defined outside all function is called as Global variable. def findsum(a,b): c=a+b return c x,y=10,20 m=findsum(x,y) print(m) Output: 30 Here the variable a, b and c is defined inside the function, so a, b and c is Local variables. The variable x, y and m is are not defined inside any function, so x, y and m is Global variables.
  • 15. K V C o d e r s L E T ’ S C R A C K C B S E C O M U P T E R S C I E N C E Using a Global variable in local scope To access a variable declared outside all functions(Global Variable) in a local scope then global statement is used. When global statement is used for a name, it restrict the function to create a local variable of that name instead the function uses the global variable. a=10 def add(x): a=x+5 print(x) add(20) print(a) Output: 25 10 a=10 def add(x): global a a=x+5 print(x) add(20) print(a) Output: 25 25 Inside the function a local variable with name a is created, so changes to the value of local variable a, doesn’t affect the value of the global variable a. Use of the global statement restrict the function to create a local variable with name a, instead the function is accessing the global variable a. So any changes made to a inside the function will affect the value of global variable a.