SlideShare a Scribd company logo
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

Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
Amrit Kaur
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
Prabhu Govind
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
cprogrammings
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Loop in C Properties & Applications
Loop in C Properties & ApplicationsLoop in C Properties & Applications
Loop in C Properties & Applications
Emroz Sardar
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
Fatima Kate Tanay
 
Conditional operators
Conditional operatorsConditional operators
Conditional operators
BU
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
ramya marichamy
 
Quick sort algorithm using slide presentation , Learn selection sort example ...
Quick sort algorithm using slide presentation , Learn selection sort example ...Quick sort algorithm using slide presentation , Learn selection sort example ...
Quick sort algorithm using slide presentation , Learn selection sort example ...
University of Science and Technology Chitttagong
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
Ahmed Swilam
 
Arrays
ArraysArrays
Tuple in python
Tuple in pythonTuple in python
Tuple in python
vikram mahendra
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
RaginiJain21
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 

What's hot (20)

Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Loop in C Properties & Applications
Loop in C Properties & ApplicationsLoop in C Properties & Applications
Loop in C Properties & Applications
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Conditional operators
Conditional operatorsConditional operators
Conditional operators
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Quick sort algorithm using slide presentation , Learn selection sort example ...
Quick sort algorithm using slide presentation , Learn selection sort example ...Quick sort algorithm using slide presentation , Learn selection sort example ...
Quick sort algorithm using slide presentation , Learn selection sort example ...
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Arrays
ArraysArrays
Arrays
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
 

Similar to Python Function.pdf

functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
Praveen M Jigajinni
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
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
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
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
MalligaarjunanN
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Rhishav Poudyal
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
SaraswathiTAsstProfI
 
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
SudhanshiBakre1
 
Function
FunctionFunction
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
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
TeshaleSiyum
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
KavithaChekuri3
 
Python functions
Python   functionsPython   functions
Python functions
Learnbay Datascience
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
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
 

Similar to Python Function.pdf (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++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
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
 
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
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
 
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
 

Recently uploaded

Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 

Recently uploaded (20)

Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 

Python Function.pdf

  • 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