SlideShare a Scribd company logo
1 of 26
Download to read offline
Python Function
Python Function
● Functions are the most important aspect of an application.
● A function can be defined as the organized block of reusable code, which can
be called whenever required.
● Python allows us to divide a large program into the basic building blocks
known as a function.
Advantage of Functions in Python
There are the following advantages of Python functions.
● Using functions, we can avoid rewriting the same logic/code again and again
in a program.
● We can call Python functions multiple times in a program and anywhere in a
program.
● We can track a large Python program easily when it is divided into multiple
functions.
● Reusability is the main achievement of Python functions.
● However, Function calling is always overhead in a Python program.
Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Syntax of Function
1. Keyword def that marks the start of the function header.
2. A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements
must have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Function Calling
● Once we have defined a function, we can call it from another function,
program, or even the Python prompt.
● To call a function we simply type the function name with appropriate
parameters.
● In python, the function definition should always be present before the function
call. Otherwise, we will get an error.
Function Calling
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
Output:
hello world
The return statement
The return statement is used at the end of the function and returns the result of the
function.
It terminates the function execution and transfers the result where the function is
called.
The return statement cannot be used outside of the function.
The return statement
Syntax
return [expression_list]
It can contain the expression which gets evaluated and value is returned to the caller
function.
If the return statement has no expression or does not exist itself in the function then it
returns the None object.
The return statement
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
Output:
The sum is: 30
Arguments in function
● The arguments are types of information which can be passed into the
function.
● The arguments are specified in the parentheses.
● We can pass any number of arguments, but they must be separate them with
a comma.
Example
#Python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))
Enter a: 10
Enter b: 20
Sum = 30
Types of arguments
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
● The required arguments are the arguments which are required to be passed at the
time of function calling with the exact match of their positions in the function
call and function definition.
● If either of the arguments is not provided in the function call, or the position of
the arguments is changed, the Python interpreter will show the error.
Required Arguments
#the function simple_interest accepts three
arguments and returns the simple interest
accordingly
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount?
"))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,t,r))
Enter the principle amount: 5000
Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0
Required Arguments
#the function calculate returns the sum of two arguments a and b
def calculate(a,b):
return a+b
>>> calculate(10) # this causes an error as we are missing a required arguments b.
Output:
TypeError: calculate() missing 1 required positional argument: 'b'
Default Arguments
● Python allows us to initialize the arguments at the function definition.
● If the value of any of this arguments is not provided at the time of function
call, then that argument can be initialized with the value given in the
definition even if the argument is not specified at the function call.
Default Arguments
def printme(name,age=22):
print("My name is",name,"and age is",age)
>>>printme("Arya")
#the variable age is not passed into the function however the default value of age
is considered in the function
>>> printme(“Arya”, 24)
#the value of age is overwritten here, 24 will be printed as age
Variable-length Arguments (*args)
● In large projects, sometimes we may not know the number of arguments to be
passed in advance.
● In such cases, Python provides us the flexibility to offer the comma-separated
values which are internally treated as tuples at the function call.
● By using the variable-length arguments, we can pass any number of arguments.
● However, at the function definition, we define the variable-length argument using
the *<variable - name >.
Variable-length Arguments (*args)
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
>>>printme("john","David","smith","nick")
Variable-length Arguments (*args)
In the above code, we passed *names as variable-length argument.
We called the function and passed values which are treated as tuple internally.
The tuple is an iterable sequence the same as the list.
To print the given values, we iterated *arg names using for loop.
Keyword arguments
● Python allows us to call the function with the keyword arguments.
● This kind of function call will enable us to pass the arguments in the random order.
● The name of the arguments is treated as the keywords and matched in the function
calling and definition.
● If the same match is found, the values of the arguments are copied in the function
definition.
Keyword arguments
#The function simple_interest(p, t, r) is called with the keyword arguments the
#order of arguments doesn't matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ", simple_interest(t=10,r=10,p=1900))
Recursive Functions
A function that calls itself is known as recursive function and the process
of calling function itself is known as recursion.
It is the process of calling a function by itself, until some specified
condition is satisfied.
It is used for repetitive computation (eg: factorial of a number) in which each
action is stated in term of previous result.
Recursive Functions
A function which calls itself is a recursive function
Example
def factorial(n):
if n==0 :
return 1
else :
return n * factorial(n-1)
>>> factorial(5)
120

More Related Content

What's hot (20)

Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Functions in c
Functions in cFunctions in c
Functions in c
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
C# loops
C# loopsC# loops
C# loops
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Function in C
Function in CFunction in C
Function in C
 
Python functions
Python functionsPython functions
Python functions
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
This pointer
This pointerThis pointer
This pointer
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 

Similar to Python Functions: Reusable Code Blocks for Any Application

functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptxSulekhJangra
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and commentMalligaarjunanN
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)Arpit Meena
 
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 modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfSudhanshiBakre1
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
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).pptxManas40552
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 

Similar to Python Functions: Reusable Code Blocks for Any Application (20)

functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
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 modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Function
FunctionFunction
Function
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Python functions
Python   functionsPython   functions
Python functions
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
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
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 

Recently uploaded

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

Python Functions: Reusable Code Blocks for Any Application

  • 2. Python Function ● Functions are the most important aspect of an application. ● A function can be defined as the organized block of reusable code, which can be called whenever required. ● Python allows us to divide a large program into the basic building blocks known as a function.
  • 3. Advantage of Functions in Python There are the following advantages of Python functions. ● Using functions, we can avoid rewriting the same logic/code again and again in a program. ● We can call Python functions multiple times in a program and anywhere in a program. ● We can track a large Python program easily when it is divided into multiple functions. ● Reusability is the main achievement of Python functions. ● However, Function calling is always overhead in a Python program.
  • 4. Types of Functions Basically, we can divide functions into the following two types: 1. Built-in functions - Functions that are built into Python. 2. User-defined functions - Functions defined by the users themselves.
  • 5. Syntax of Function def function_name(parameters): """docstring""" statement(s)
  • 6. Syntax of Function 1. Keyword def that marks the start of the function header. 2. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python. 3. Parameters (arguments) through which we pass values to a function. They are optional. 4. A colon (:) to mark the end of the function header. 5. Optional documentation string (docstring) to describe what the function does. 6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces). 7. An optional return statement to return a value from the function.
  • 7. Function Calling ● Once we have defined a function, we can call it from another function, program, or even the Python prompt. ● To call a function we simply type the function name with appropriate parameters. ● In python, the function definition should always be present before the function call. Otherwise, we will get an error.
  • 8. Function Calling #function definition def hello_world(): print("hello world") # function calling hello_world() Output: hello world
  • 9. The return statement The return statement is used at the end of the function and returns the result of the function. It terminates the function execution and transfers the result where the function is called. The return statement cannot be used outside of the function.
  • 10. The return statement Syntax return [expression_list] It can contain the expression which gets evaluated and value is returned to the caller function. If the return statement has no expression or does not exist itself in the function then it returns the None object.
  • 11. The return statement # Defining function def sum(): a = 10 b = 20 c = a+b return c # calling sum() function in print statement print("The sum is:",sum()) Output: The sum is: 30
  • 12. Arguments in function ● The arguments are types of information which can be passed into the function. ● The arguments are specified in the parentheses. ● We can pass any number of arguments, but they must be separate them with a comma.
  • 13. Example #Python function to calculate the sum of two variables #defining the function def sum (a,b): return a+b; #taking values from the user a = int(input("Enter a: ")) b = int(input("Enter b: ")) #printing the sum of a and b print("Sum = ",sum(a,b)) Enter a: 10 Enter b: 20 Sum = 30
  • 14. Types of arguments 1. Required arguments 2. Keyword arguments 3. Default arguments 4. Variable-length arguments
  • 15. Required Arguments ● The required arguments are the arguments which are required to be passed at the time of function calling with the exact match of their positions in the function call and function definition. ● If either of the arguments is not provided in the function call, or the position of the arguments is changed, the Python interpreter will show the error.
  • 16. Required Arguments #the function simple_interest accepts three arguments and returns the simple interest accordingly def simple_interest(p,t,r): return (p*t*r)/100 p = float(input("Enter the principle amount? ")) r = float(input("Enter the rate of interest? ")) t = float(input("Enter the time in years? ")) print("Simple Interest: ",simple_interest(p,t,r)) Enter the principle amount: 5000 Enter the rate of interest: 5 Enter the time in years: 3 Simple Interest: 750.0
  • 17. Required Arguments #the function calculate returns the sum of two arguments a and b def calculate(a,b): return a+b >>> calculate(10) # this causes an error as we are missing a required arguments b. Output: TypeError: calculate() missing 1 required positional argument: 'b'
  • 18. Default Arguments ● Python allows us to initialize the arguments at the function definition. ● If the value of any of this arguments is not provided at the time of function call, then that argument can be initialized with the value given in the definition even if the argument is not specified at the function call.
  • 19. Default Arguments def printme(name,age=22): print("My name is",name,"and age is",age) >>>printme("Arya") #the variable age is not passed into the function however the default value of age is considered in the function >>> printme(“Arya”, 24) #the value of age is overwritten here, 24 will be printed as age
  • 20. Variable-length Arguments (*args) ● In large projects, sometimes we may not know the number of arguments to be passed in advance. ● In such cases, Python provides us the flexibility to offer the comma-separated values which are internally treated as tuples at the function call. ● By using the variable-length arguments, we can pass any number of arguments. ● However, at the function definition, we define the variable-length argument using the *<variable - name >.
  • 21. Variable-length Arguments (*args) def printme(*names): print("type of passed argument is ",type(names)) print("printing the passed arguments...") for name in names: print(name) >>>printme("john","David","smith","nick")
  • 22. Variable-length Arguments (*args) In the above code, we passed *names as variable-length argument. We called the function and passed values which are treated as tuple internally. The tuple is an iterable sequence the same as the list. To print the given values, we iterated *arg names using for loop.
  • 23. Keyword arguments ● Python allows us to call the function with the keyword arguments. ● This kind of function call will enable us to pass the arguments in the random order. ● The name of the arguments is treated as the keywords and matched in the function calling and definition. ● If the same match is found, the values of the arguments are copied in the function definition.
  • 24. Keyword arguments #The function simple_interest(p, t, r) is called with the keyword arguments the #order of arguments doesn't matter in this case def simple_interest(p,t,r): return (p*t*r)/100 print("Simple Interest: ", simple_interest(t=10,r=10,p=1900))
  • 25. Recursive Functions A function that calls itself is known as recursive function and the process of calling function itself is known as recursion. It is the process of calling a function by itself, until some specified condition is satisfied. It is used for repetitive computation (eg: factorial of a number) in which each action is stated in term of previous result.
  • 26. Recursive Functions A function which calls itself is a recursive function Example def factorial(n): if n==0 : return 1 else : return n * factorial(n-1) >>> factorial(5) 120