SlideShare a Scribd company logo
Python Programming – Unit 3
Part – 1
Functions
1
https://www.scribd.com/presentation/831767862/
Python-Unit2-Loop
Dr.VIDHYA B
ASSISTANT PROFESSOR & HEAD
Department of Computer Technology
Sri Ramakrishna College of Arts and Science
Coimbatore - 641 006
Tamil Nadu, India
February 23, 2025 Functions 2
February 23, 2025 Functions 3
February 23, 2025 Functions 4
WHAT IS A FUNCTION?
-a block of statements that can be used repeatedly in
a program
- will not execute immediately when a page loads
- will be executed by a call to the function
- takes one or more input in the form of parameter
- does some processing using the input and returns a
value.
February 23, 2025 Functions 5
USER DEFINED FUNCTION
Func1() is called the
program control is passed
to the first statement in the
function.
All statements in the
functions are executed and
then the program control is
passed to the statement
following the one that
called the function
func1()calls func2().
func1() is known as calling
function.
func2() is known as called
function.
func1() can call as many
functions as many times.
February 23, 2025 Functions 6
NEED FOR FUNCTIONS
• Dividing the program into separate well defined
functions , helps each function to be written
separately .
• Simplifies process of program development
February 23, 2025 Functions 7
NEED FOR FUNCTIONS
• Understanding, coding and testing multiple separate
functions are easier.
• Big program without function lead to large number
of coding and maintain the program is mess. In
microcomputer memory space is less, hence it is a
serous issue.
• Libraries in python are predefined and pretested,
programmers are able to use directly hence speeds
up the program development.
• Programmers can design own functions and use
from different points.
February 23, 2025 Functions 8
NEED FOR FUNCTIONS
• Large Programs follow code reuse hence DRY
principle is used – Don’t Repeat Yourself
• Bad Code uses – WET principle Write Everything
Twice or We Enjoy Typing
February 23, 2025 Functions 9
User Define Functions
- option to create user’s own functions
- two parts in a user defined function
(i) Calling Function – The function which invokes
the action
(ii) Called Function - The Function which does
the job by receiving the call
from the calling function
February 23, 2025 Functions 10
CALLING AND CALLED FUNCTION
Calling Function:
The Function
which invokes the
action
Called Function:
The Function
which does the job by
receiving the call from
the Calling function
February 23, 2025 Functions 11
FUNCTION Definition
Terminology for functions:
- Input Function takes is known as arguments/ parameters.
- Called function returns some result back to calling
function, it is said to return the result.
- Calling function may or may not pass parameters to
called function.
- Function declaration is the a declaration statement
identifies a function name, arguments & type of data
returned.
- Function definition consists of function header (identifies
the function), followed by the body of the function.
February 23, 2025 Functions 12
FUNCTION Definition
- Function blocks starts with keyword def .
- Keyword followed by function name with()
- After () : is placed
- Parameters or arguments are placed inside()
- First statement can be optional, docstring describe
what function does.
- Code block within function to be indented.
- Function may have return expression
- Function name can be assigned to a variable.
}
February 23, 2025 Functions 13
FUNCTION Definition
Function definition consists of 2 parts:
- Function Header & - Function Body
- Where def => Keyword for defining a function
- Function_name => Name of the function
- Parameter list => Data to be passed to be used by
the function for operation
- Function body => contains a collection of
statements that define what the function does.
def function_name( parameter list )
body of the function
}
February 23, 2025 Functions 14
EXAMPLE: FUNCTION DEFINITION
( CALLED FUNCTION)
def diff (x ,y) #function to subtract to numbers
return x-y
a=20
b=10
operation=diff #function name assigned to a
variable
print(operation(a,b)) #function called – variable
name
Output: 10
February 23, 2025 Functions 15
FUNCTION CALL
(CALLING FUNCTION)
- tells about a function name and how to call the
function
- It has the following form…
- Function_name => Name of the function
- Parameter list => Data to be passed to be used by
the function for operation
Function_name(Parameter list)
February 23, 2025 Functions 16
PASSING PARAMETER
- Data to be passed to be used by the function for
operation
Types of Parameter:
1) Actual Parameter –
Parameters passed to the function actually- used
in function call
2) Formal Parameter –
Parameters received by the function
When a function is called checks for number and
types of arguments used and return value type.
February 23, 2025 Functions 17
Function Parameters
- Function Name, number of arguemnts in the
function call must be the same as function
definition
def func(i,j)
print(“hello world”,i,j)
func(5)
def func(i)
print(“hello world”,i)
func(5,5)
def func(i)
print(“hello world”,i)
j=10
func(j)
O/P:
Hello world 10
def func(i)
print(“hello world” +i)
func(5)
February 23, 2025 Functions 18
Variable Scope and Life time
Scope – Part of a
program in which a
variable is accessible
Life time of the variable-
Duration for which the
variable exists
February 23, 2025 Functions 19
LOCALAND GLOBAL VARIABLES
- refers to the area of the program where the
variables can be accessed after its declaration
- variable declared within a function is different
from a variable declared outside a function.
POSITION TYPE
Inside a Function or a
Block
Local Variable
Outside of all functions Global Variable
February 23, 2025 Functions 20
Scope of a Variable (Example)
greeting = "Hello" # Global Variable
def greeting_world():
world = "World" #Local Variable
print(greeting, world)
def greeting_name(name):
print(greeting, name)
greeting_world()
greeting_name(“India")
Output:
Hello World
Hello India
February 23, 2025 Functions 21
Comparison
February 23, 2025 Functions 22
The Return Statement
• Every function has an implicit return statement.
• Implicit return does not returns nothing to it
caller and said to return none.
• But can be changed using return statement
Syntax:
return[expression]
Return statements used for 2 things:
- Return a value to the caller.
- To end and exit a function and go back to its
caller.
February 23, 2025 Functions 23
FUNCTION WITH RETURN VALUE
def cube(x):
return(x*x*x)
num=10
result=cube(num)
print(“the cube of ”, num “is”,
result)
Output:
cube of 10 is 1000
Points to Remember:
- Return Statement
must appear within
function
- Once a value is
returned from a
function, immediately
exists from the
function.
- Any code written after
the return statement
will not be executed
February 23, 2025 Functions 24
More on Defining Functions
More on
defining
Functions
Required
Arguments
KEYWORD
ARGUMENTS
VARIABLE-
LENGTH
ARGUMENTS
Default
arguments
February 23, 2025 Functions 25
More on Defining Functions
Required Arguments – The arguments are passed to a
function in a correct positional order.
February 23, 2025 Functions 26
More on Defining Functions
Keyword Arguments – The order of the arguments
can be changed. Values are not assigned to
arguments according to the position but based on
their name.
Benefits:
- If argument is skipped
- If function call changes its order
Points to Remember:
- All the keyword arguments passed should match one
of the arguments accepted by the function.
- The order of keyword arguments is not important
- In no case an argument should receive a value more
than once.
February 23, 2025 Functions 27
More on Defining Functions
February 23, 2025 Functions 28
More on Defining Functions
Default Arguments – Allows function arguments
can have default values.
Default value to an argument is provided using
assignment operator =.
Default values can be specified for one or more
arguments.
Points to Remember:
- If default argument is present should be written after
non-default arguments.
- The order of keyword arguments is not important
- In no case an argument should receive a value more
than once.
February 23, 2025 Functions 29
More on Defining Functions
February 23, 2025 Functions 30
More on Defining Functions
Variable-Length Arguments – Allows function to
have arbitrary number of arguments.
Use * before the parameter name.
Points to Remember:
- Basically forms a tuple.
- Inside Called function, for loop is used to access the
arguments
- If present in function definition should be the last in
the list of formal parameters
- Any formal parameters written after variable is only
keyword –only arguments.
February 23, 2025 Functions 31
More on Defining Functions
Syntax:
def function_name([arg1, arg2,….] *var_args-tuple):
Function statements
Return[expression]
February 23, 2025 Functions 32
February 23, 2025 Functions 33
WHAT IS RECURSION ?
A repeated
Process, or a
Definition or a
Procedure
February 23, 2025 Functions 34
WHAT IS RECURSIVE?
- breaking down a problem into smaller and
smaller sub problems
- until the problem is made small enough that it can
be solved trivially
February 23, 2025 Functions 35
RECURSIVE FUNCTION
- process of calling a function by itself
- The function call is within the same function
- Every recursive has two major cases:
*Base Case – problem solved directly without
making any further calls
*Recursive case – divided into subparts, function call
itself, result obtained by combining the solutions of
simpler parts.
February 23, 2025 Functions 36
Recursive Function (Example)
def fact(n):
if (n == 0 or n= = 1):
return 1
else:
return n* fact(n-1)
n = int(input("Enter a number: "))
print(“Factorial of",n,"is:“,fact(n))
Output:
Enter a number: 5
Factorial of 5 is 120
February 23, 2025 Functions 37
Recursive Function (Example)
Steps:
1) Specify the base case which will
stop the function from making a
call to itself.
2) Check to see current value
matches with the value of base
case, if yes , process nad return
value
3) Divide the problem into smaller
or simpler problem.
4) Call the function
on the subproblem.
5) Combine the
results of the
subproblem.
6) Return the results
of the entire problem.
February 23, 2025 Functions 38
RECURSIVE FUNCTION

More Related Content

Similar to Python_Functions_Modules_ User define Functions- (20)

ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
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
 
functions new.pptx
functions new.pptxfunctions new.pptx
functions new.pptx
bhuvanalakshmik2
 
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
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdffunctionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
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
 
Ch-5.pdf
Ch-5.pdfCh-5.pdf
Ch-5.pdf
R.K.College of engg & Tech
 
Ch-5.pdf
Ch-5.pdfCh-5.pdf
Ch-5.pdf
R.K.College of engg & Tech
 
Functions in python, types of functions in python
Functions in python, types of functions in pythonFunctions in python, types of functions in python
Functions in python, types of functions in python
SherinRappai
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
NehaSpillai1
 
FUNCTIONS.pptx
FUNCTIONS.pptxFUNCTIONS.pptx
FUNCTIONS.pptx
KalashJain27
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf2-functions.pptx_20240619_085610_0000.pdf
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
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
 
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
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdffunctionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
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
 
Functions in python, types of functions in python
Functions in python, types of functions in pythonFunctions in python, types of functions in python
Functions in python, types of functions in python
SherinRappai
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
NehaSpillai1
 

More from VidhyaB10 (12)

Preprocessing - Data Integration Tuple Duplication
Preprocessing - Data Integration Tuple DuplicationPreprocessing - Data Integration Tuple Duplication
Preprocessing - Data Integration Tuple Duplication
VidhyaB10
 
Major Tasks in Data Preprocessing - Data cleaning
Major Tasks in Data Preprocessing - Data cleaningMajor Tasks in Data Preprocessing - Data cleaning
Major Tasks in Data Preprocessing - Data cleaning
VidhyaB10
 
Applications ,Issues & Technology in Data mining -
Applications ,Issues & Technology in Data mining -Applications ,Issues & Technology in Data mining -
Applications ,Issues & Technology in Data mining -
VidhyaB10
 
Python Visualization API Primersubplots
Python Visualization  API PrimersubplotsPython Visualization  API Primersubplots
Python Visualization API Primersubplots
VidhyaB10
 
Python _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functionsPython _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functions
VidhyaB10
 
Datamining - Introduction - Knowledge Discovery in Databases
Datamining  - Introduction - Knowledge Discovery in DatabasesDatamining  - Introduction - Knowledge Discovery in Databases
Datamining - Introduction - Knowledge Discovery in Databases
VidhyaB10
 
INSTRUCTION PROCESSOR DESIGN Computer system architecture
INSTRUCTION PROCESSOR DESIGN Computer system architectureINSTRUCTION PROCESSOR DESIGN Computer system architecture
INSTRUCTION PROCESSOR DESIGN Computer system architecture
VidhyaB10
 
Disk Scheduling in OS computer deals with multiple processes over a period of...
Disk Scheduling in OS computer deals with multiple processes over a period of...Disk Scheduling in OS computer deals with multiple processes over a period of...
Disk Scheduling in OS computer deals with multiple processes over a period of...
VidhyaB10
 
Unit 2 digital fundamentals boolean func.pptx
Unit 2 digital fundamentals boolean func.pptxUnit 2 digital fundamentals boolean func.pptx
Unit 2 digital fundamentals boolean func.pptx
VidhyaB10
 
Digital Fundamental - Binary Codes-Logic Gates
Digital Fundamental - Binary Codes-Logic GatesDigital Fundamental - Binary Codes-Logic Gates
Digital Fundamental - Binary Codes-Logic Gates
VidhyaB10
 
unit 5-files.pptx
unit 5-files.pptxunit 5-files.pptx
unit 5-files.pptx
VidhyaB10
 
Python_Unit1_Introduction.pptx
Python_Unit1_Introduction.pptxPython_Unit1_Introduction.pptx
Python_Unit1_Introduction.pptx
VidhyaB10
 
Preprocessing - Data Integration Tuple Duplication
Preprocessing - Data Integration Tuple DuplicationPreprocessing - Data Integration Tuple Duplication
Preprocessing - Data Integration Tuple Duplication
VidhyaB10
 
Major Tasks in Data Preprocessing - Data cleaning
Major Tasks in Data Preprocessing - Data cleaningMajor Tasks in Data Preprocessing - Data cleaning
Major Tasks in Data Preprocessing - Data cleaning
VidhyaB10
 
Applications ,Issues & Technology in Data mining -
Applications ,Issues & Technology in Data mining -Applications ,Issues & Technology in Data mining -
Applications ,Issues & Technology in Data mining -
VidhyaB10
 
Python Visualization API Primersubplots
Python Visualization  API PrimersubplotsPython Visualization  API Primersubplots
Python Visualization API Primersubplots
VidhyaB10
 
Python _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functionsPython _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functions
VidhyaB10
 
Datamining - Introduction - Knowledge Discovery in Databases
Datamining  - Introduction - Knowledge Discovery in DatabasesDatamining  - Introduction - Knowledge Discovery in Databases
Datamining - Introduction - Knowledge Discovery in Databases
VidhyaB10
 
INSTRUCTION PROCESSOR DESIGN Computer system architecture
INSTRUCTION PROCESSOR DESIGN Computer system architectureINSTRUCTION PROCESSOR DESIGN Computer system architecture
INSTRUCTION PROCESSOR DESIGN Computer system architecture
VidhyaB10
 
Disk Scheduling in OS computer deals with multiple processes over a period of...
Disk Scheduling in OS computer deals with multiple processes over a period of...Disk Scheduling in OS computer deals with multiple processes over a period of...
Disk Scheduling in OS computer deals with multiple processes over a period of...
VidhyaB10
 
Unit 2 digital fundamentals boolean func.pptx
Unit 2 digital fundamentals boolean func.pptxUnit 2 digital fundamentals boolean func.pptx
Unit 2 digital fundamentals boolean func.pptx
VidhyaB10
 
Digital Fundamental - Binary Codes-Logic Gates
Digital Fundamental - Binary Codes-Logic GatesDigital Fundamental - Binary Codes-Logic Gates
Digital Fundamental - Binary Codes-Logic Gates
VidhyaB10
 
unit 5-files.pptx
unit 5-files.pptxunit 5-files.pptx
unit 5-files.pptx
VidhyaB10
 
Python_Unit1_Introduction.pptx
Python_Unit1_Introduction.pptxPython_Unit1_Introduction.pptx
Python_Unit1_Introduction.pptx
VidhyaB10
 
Ad

Recently uploaded (20)

Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
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
 
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
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
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)
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
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.
 
la storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglesela storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglese
LetiziaLucente
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
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
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
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
 
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
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
la storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglesela storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglese
LetiziaLucente
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
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
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
Ad

Python_Functions_Modules_ User define Functions-

  • 1. Python Programming – Unit 3 Part – 1 Functions 1 https://www.scribd.com/presentation/831767862/ Python-Unit2-Loop Dr.VIDHYA B ASSISTANT PROFESSOR & HEAD Department of Computer Technology Sri Ramakrishna College of Arts and Science Coimbatore - 641 006 Tamil Nadu, India
  • 2. February 23, 2025 Functions 2
  • 3. February 23, 2025 Functions 3
  • 4. February 23, 2025 Functions 4 WHAT IS A FUNCTION? -a block of statements that can be used repeatedly in a program - will not execute immediately when a page loads - will be executed by a call to the function - takes one or more input in the form of parameter - does some processing using the input and returns a value.
  • 5. February 23, 2025 Functions 5 USER DEFINED FUNCTION Func1() is called the program control is passed to the first statement in the function. All statements in the functions are executed and then the program control is passed to the statement following the one that called the function func1()calls func2(). func1() is known as calling function. func2() is known as called function. func1() can call as many functions as many times.
  • 6. February 23, 2025 Functions 6 NEED FOR FUNCTIONS • Dividing the program into separate well defined functions , helps each function to be written separately . • Simplifies process of program development
  • 7. February 23, 2025 Functions 7 NEED FOR FUNCTIONS • Understanding, coding and testing multiple separate functions are easier. • Big program without function lead to large number of coding and maintain the program is mess. In microcomputer memory space is less, hence it is a serous issue. • Libraries in python are predefined and pretested, programmers are able to use directly hence speeds up the program development. • Programmers can design own functions and use from different points.
  • 8. February 23, 2025 Functions 8 NEED FOR FUNCTIONS • Large Programs follow code reuse hence DRY principle is used – Don’t Repeat Yourself • Bad Code uses – WET principle Write Everything Twice or We Enjoy Typing
  • 9. February 23, 2025 Functions 9 User Define Functions - option to create user’s own functions - two parts in a user defined function (i) Calling Function – The function which invokes the action (ii) Called Function - The Function which does the job by receiving the call from the calling function
  • 10. February 23, 2025 Functions 10 CALLING AND CALLED FUNCTION Calling Function: The Function which invokes the action Called Function: The Function which does the job by receiving the call from the Calling function
  • 11. February 23, 2025 Functions 11 FUNCTION Definition Terminology for functions: - Input Function takes is known as arguments/ parameters. - Called function returns some result back to calling function, it is said to return the result. - Calling function may or may not pass parameters to called function. - Function declaration is the a declaration statement identifies a function name, arguments & type of data returned. - Function definition consists of function header (identifies the function), followed by the body of the function.
  • 12. February 23, 2025 Functions 12 FUNCTION Definition - Function blocks starts with keyword def . - Keyword followed by function name with() - After () : is placed - Parameters or arguments are placed inside() - First statement can be optional, docstring describe what function does. - Code block within function to be indented. - Function may have return expression - Function name can be assigned to a variable. }
  • 13. February 23, 2025 Functions 13 FUNCTION Definition Function definition consists of 2 parts: - Function Header & - Function Body - Where def => Keyword for defining a function - Function_name => Name of the function - Parameter list => Data to be passed to be used by the function for operation - Function body => contains a collection of statements that define what the function does. def function_name( parameter list ) body of the function }
  • 14. February 23, 2025 Functions 14 EXAMPLE: FUNCTION DEFINITION ( CALLED FUNCTION) def diff (x ,y) #function to subtract to numbers return x-y a=20 b=10 operation=diff #function name assigned to a variable print(operation(a,b)) #function called – variable name Output: 10
  • 15. February 23, 2025 Functions 15 FUNCTION CALL (CALLING FUNCTION) - tells about a function name and how to call the function - It has the following form… - Function_name => Name of the function - Parameter list => Data to be passed to be used by the function for operation Function_name(Parameter list)
  • 16. February 23, 2025 Functions 16 PASSING PARAMETER - Data to be passed to be used by the function for operation Types of Parameter: 1) Actual Parameter – Parameters passed to the function actually- used in function call 2) Formal Parameter – Parameters received by the function When a function is called checks for number and types of arguments used and return value type.
  • 17. February 23, 2025 Functions 17 Function Parameters - Function Name, number of arguemnts in the function call must be the same as function definition def func(i,j) print(“hello world”,i,j) func(5) def func(i) print(“hello world”,i) func(5,5) def func(i) print(“hello world”,i) j=10 func(j) O/P: Hello world 10 def func(i) print(“hello world” +i) func(5)
  • 18. February 23, 2025 Functions 18 Variable Scope and Life time Scope – Part of a program in which a variable is accessible Life time of the variable- Duration for which the variable exists
  • 19. February 23, 2025 Functions 19 LOCALAND GLOBAL VARIABLES - refers to the area of the program where the variables can be accessed after its declaration - variable declared within a function is different from a variable declared outside a function. POSITION TYPE Inside a Function or a Block Local Variable Outside of all functions Global Variable
  • 20. February 23, 2025 Functions 20 Scope of a Variable (Example) greeting = "Hello" # Global Variable def greeting_world(): world = "World" #Local Variable print(greeting, world) def greeting_name(name): print(greeting, name) greeting_world() greeting_name(“India") Output: Hello World Hello India
  • 21. February 23, 2025 Functions 21 Comparison
  • 22. February 23, 2025 Functions 22 The Return Statement • Every function has an implicit return statement. • Implicit return does not returns nothing to it caller and said to return none. • But can be changed using return statement Syntax: return[expression] Return statements used for 2 things: - Return a value to the caller. - To end and exit a function and go back to its caller.
  • 23. February 23, 2025 Functions 23 FUNCTION WITH RETURN VALUE def cube(x): return(x*x*x) num=10 result=cube(num) print(“the cube of ”, num “is”, result) Output: cube of 10 is 1000 Points to Remember: - Return Statement must appear within function - Once a value is returned from a function, immediately exists from the function. - Any code written after the return statement will not be executed
  • 24. February 23, 2025 Functions 24 More on Defining Functions More on defining Functions Required Arguments KEYWORD ARGUMENTS VARIABLE- LENGTH ARGUMENTS Default arguments
  • 25. February 23, 2025 Functions 25 More on Defining Functions Required Arguments – The arguments are passed to a function in a correct positional order.
  • 26. February 23, 2025 Functions 26 More on Defining Functions Keyword Arguments – The order of the arguments can be changed. Values are not assigned to arguments according to the position but based on their name. Benefits: - If argument is skipped - If function call changes its order Points to Remember: - All the keyword arguments passed should match one of the arguments accepted by the function. - The order of keyword arguments is not important - In no case an argument should receive a value more than once.
  • 27. February 23, 2025 Functions 27 More on Defining Functions
  • 28. February 23, 2025 Functions 28 More on Defining Functions Default Arguments – Allows function arguments can have default values. Default value to an argument is provided using assignment operator =. Default values can be specified for one or more arguments. Points to Remember: - If default argument is present should be written after non-default arguments. - The order of keyword arguments is not important - In no case an argument should receive a value more than once.
  • 29. February 23, 2025 Functions 29 More on Defining Functions
  • 30. February 23, 2025 Functions 30 More on Defining Functions Variable-Length Arguments – Allows function to have arbitrary number of arguments. Use * before the parameter name. Points to Remember: - Basically forms a tuple. - Inside Called function, for loop is used to access the arguments - If present in function definition should be the last in the list of formal parameters - Any formal parameters written after variable is only keyword –only arguments.
  • 31. February 23, 2025 Functions 31 More on Defining Functions Syntax: def function_name([arg1, arg2,….] *var_args-tuple): Function statements Return[expression]
  • 32. February 23, 2025 Functions 32
  • 33. February 23, 2025 Functions 33 WHAT IS RECURSION ? A repeated Process, or a Definition or a Procedure
  • 34. February 23, 2025 Functions 34 WHAT IS RECURSIVE? - breaking down a problem into smaller and smaller sub problems - until the problem is made small enough that it can be solved trivially
  • 35. February 23, 2025 Functions 35 RECURSIVE FUNCTION - process of calling a function by itself - The function call is within the same function - Every recursive has two major cases: *Base Case – problem solved directly without making any further calls *Recursive case – divided into subparts, function call itself, result obtained by combining the solutions of simpler parts.
  • 36. February 23, 2025 Functions 36 Recursive Function (Example) def fact(n): if (n == 0 or n= = 1): return 1 else: return n* fact(n-1) n = int(input("Enter a number: ")) print(“Factorial of",n,"is:“,fact(n)) Output: Enter a number: 5 Factorial of 5 is 120
  • 37. February 23, 2025 Functions 37 Recursive Function (Example) Steps: 1) Specify the base case which will stop the function from making a call to itself. 2) Check to see current value matches with the value of base case, if yes , process nad return value 3) Divide the problem into smaller or simpler problem. 4) Call the function on the subproblem. 5) Combine the results of the subproblem. 6) Return the results of the entire problem.
  • 38. February 23, 2025 Functions 38 RECURSIVE FUNCTION