SlideShare a Scribd company logo
Functions in Python
Function
• A function is a relationship or mapping between one or more inputs and a
set of outputs. In mathematics, a function is typically represented like this:
• Here, f is a function that operates on the inputs x and y. The output of the
function is z. However, programming functions are much more generalized
and versatile than this mathematical definition. In fact, appropriate
function definition and use is so critical to proper software development
that virtually all modern programming languages support both built-in
and user-defined functions.
• In programming, a function is a self-contained block of code that
encapsulates a specific task or related group of tasks.
The Importance of Python Functions
Virtually all programming languages used today support a
form of user-defined functions, although they aren’t always
called functions. In other languages, you may see them
referred to as one of the following:
• Subroutines
• Procedures
• Methods
• Subprograms
Functions in Python and its types for beginners
Types of function
• There are three types of functions in Python:
• Built-in functions, such as help() to ask for help, min() to get the
minimum value, print() to print an object to the terminal,… You can
find an overview with more of these functions here.
• User-Defined Functions (UDFs), which are functions that users
create to help them out; And
• Anonymous functions, which are also called lambda functions
because they are not declared with the standard def keyword.
Functions vs. methods
• A method refers to a function which is part of a class. You
access it with an instance or object of the class. A function
doesn’t have this restriction: it just refers to a standalone
function. This means that all methods are functions, but not
all functions are methods.
Parameters vs. arguments
• Parameters are the names used when defining a function or
a method, and into which arguments will be mapped. In
other words, arguments are the things which are supplied
to any function or method call, while the function or method
code refers to the arguments by their parameter names.
User-Defined Functions (UDFs)
• The four steps to defining a function in Python are the following:
• Use the keyword def to declare the function and follow this up with the function
name.
• Add parameters to the function: they should be within the parentheses of the
function. End your line with a colon.
• Add statements that the functions should execute.
• End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None.
Functions in Python and its types for beginners
Component Meaning
def The keyword that informs
Python that a function is being
defined
<function_name> A valid Python identifier that
names the function
<parameters> An optional, comma-separated
list of parameters that may be
passed to the function
: Punctuation that denotes the
end of the Python function
header (the name and
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return
hello()
Argument Passing
Positional Arguments
• The most straightforward way to pass arguments to a Python
function is with positional arguments (also called required
arguments). In the function definition, you specify a comma-
separated list of parameters inside the parentheses:
>>> def f(qty, item, price):
... print(f'{qty} {item} cost ${price:.2f}')
...
>>> f(6, 'bananas', 1.74)
6 bananas cost $1.74
• Keyword Arguments
If you want to make sure that you call all the parameters in the right
order, you can use the keyword arguments in your function call. You
use these to identify the arguments by their parameter name.
>>> f(qty=6, item='bananas', price=1.74)
6 bananas cost $1.74
Using keyword arguments lifts the restriction on argument order.
Each keyword argument explicitly designates a specific parameter by
name, so you can specify them in any order and Python will still
know which argument goes with which parameter:
• Default Parameters
• If a parameter specified in a Python function definition has the form
<name>=<value>, then <value> becomes a default value for that
parameter. Parameters defined this way are referred to as default or
optional parameters.
>>> def f(qty=6, item='bananas', price=1.74):
... print(f'{qty} {item} cost ${price:.2f}')
...
>>> f(4, 'apples', 2.24)
4 apples cost $2.24
>>> f(4, 'apples')
4 apples cost $1.74
>>> f(4)
4 bananas cost $1.74
>>> f()
6 bananas cost $1.74
>>> f(item='kumquats', qty=9)
9 kumquats cost $1.74
>>> f(price=2.29)
6 bananas cost $2.29
Functions in Python and its types for beginners
Python Modules
• Modular programming refers to the process of breaking a
large, unwieldy programming task into separate, smaller,
more manageable subtasks or modules. Individual modules
can then be cobbled together like building blocks to create a
larger application.
• There are several advantages to modularizing code in a
large application:
Simplicity: Rather than focusing on the entire problem at hand, a
module typically focuses on one relatively small portion of the
problem. If you’re working on a single module, you’ll have a smaller
problem domain to wrap your head around. This makes
development easier and less error-prone.
• Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains. If modules are written in a
way that minimizes interdependency, there is decreased likelihood that
modifications to a single module will have an impact on other parts of the
program. (You may even be able to make changes to a module without having
any knowledge of the application outside that module.) This makes it more
viable for a team of many programmers to work collaboratively on a large
application.
• Reusability: Functionality defined in a single module can be easily reused
(through an appropriately defined interface) by other parts of the application.
This eliminates the need to duplicate code.
• Scoping: Modules typically define a separate namespace, which helps avoid
collisions between identifiers in different areas of a program.
Python Modules:
• There are three different ways to define a module in
Python:
• A module can be written in Python itself.
• A module can be written in C and loaded dynamically at run-
time, like the re (regular expression) module.
• A built-in module is intrinsically contained in the interpreter,
like the itertools module.
The import Statement
• Module contents are made available to the caller with the
import statement. The import statement takes many
different forms, shown below.
import <module_name>
The simplest form is the one already shown above:
import <module_name>
from <module_name> import
<name(s)>
• An alternate form of the import statement allows individual
objects from the module to be imported directly into the
caller’s symbol table:
• from <module_name> import <name(s)>
Ad

More Related Content

Similar to Functions in Python and its types for beginners (20)

Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
arvdexamsection
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).pptchapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
Functions
FunctionsFunctions
Functions
Lakshmi Sarvani Videla
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptxpython-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
avishekpradhan24
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions ConceptsFunctions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Functions in c
Functions in cFunctions in c
Functions in c
reshmy12
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
Functions
FunctionsFunctions
Functions
Gaurav Subham
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
Krushal Kakadia
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).pptchapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptxpython-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
avishekpradhan24
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions ConceptsFunctions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Functions in c
Functions in cFunctions in c
Functions in c
reshmy12
 
python slides introduction interrupt.ppt
python slides introduction interrupt.pptpython slides introduction interrupt.ppt
python slides introduction interrupt.ppt
Vinod Deenathayalan
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
Yagna15
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 

More from Mohammad Usman (18)

Transformation in Education from past to current
Transformation in Education from past to currentTransformation in Education from past to current
Transformation in Education from past to current
Mohammad Usman
 
AI for Data Analysis and Visualization.pdf
AI for Data Analysis and Visualization.pdfAI for Data Analysis and Visualization.pdf
AI for Data Analysis and Visualization.pdf
Mohammad Usman
 
Lists and its functions in python for beginners
Lists and its functions in python for beginnersLists and its functions in python for beginners
Lists and its functions in python for beginners
Mohammad Usman
 
Modules and its usage in python for beginners
Modules and its usage in python for beginnersModules and its usage in python for beginners
Modules and its usage in python for beginners
Mohammad Usman
 
Credit Card Fraud Detection Using AI.pptx
Credit Card Fraud Detection Using AI.pptxCredit Card Fraud Detection Using AI.pptx
Credit Card Fraud Detection Using AI.pptx
Mohammad Usman
 
Exploring Search Engines and their usage online
Exploring Search Engines and their usage onlineExploring Search Engines and their usage online
Exploring Search Engines and their usage online
Mohammad Usman
 
Web Technologies Types available on the internet
Web Technologies Types available on the internetWeb Technologies Types available on the internet
Web Technologies Types available on the internet
Mohammad Usman
 
AI open tools for Research.pptx
AI open tools for Research.pptxAI open tools for Research.pptx
AI open tools for Research.pptx
Mohammad Usman
 
Open AI Tools for Data Analytics
Open AI Tools for Data AnalyticsOpen AI Tools for Data Analytics
Open AI Tools for Data Analytics
Mohammad Usman
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Mohammad Usman
 
Object oriented programming with c++
Object oriented programming with c++Object oriented programming with c++
Object oriented programming with c++
Mohammad Usman
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
Career Guide
Career GuideCareer Guide
Career Guide
Mohammad Usman
 
C areer banner
C areer bannerC areer banner
C areer banner
Mohammad Usman
 
Career counselling banner
Career counselling bannerCareer counselling banner
Career counselling banner
Mohammad Usman
 
Career ccc
Career cccCareer ccc
Career ccc
Mohammad Usman
 
Career ccc hindi
Career ccc hindiCareer ccc hindi
Career ccc hindi
Mohammad Usman
 
Literacy for or_against_the_poor_seminar
Literacy for or_against_the_poor_seminarLiteracy for or_against_the_poor_seminar
Literacy for or_against_the_poor_seminar
Mohammad Usman
 
Transformation in Education from past to current
Transformation in Education from past to currentTransformation in Education from past to current
Transformation in Education from past to current
Mohammad Usman
 
AI for Data Analysis and Visualization.pdf
AI for Data Analysis and Visualization.pdfAI for Data Analysis and Visualization.pdf
AI for Data Analysis and Visualization.pdf
Mohammad Usman
 
Lists and its functions in python for beginners
Lists and its functions in python for beginnersLists and its functions in python for beginners
Lists and its functions in python for beginners
Mohammad Usman
 
Modules and its usage in python for beginners
Modules and its usage in python for beginnersModules and its usage in python for beginners
Modules and its usage in python for beginners
Mohammad Usman
 
Credit Card Fraud Detection Using AI.pptx
Credit Card Fraud Detection Using AI.pptxCredit Card Fraud Detection Using AI.pptx
Credit Card Fraud Detection Using AI.pptx
Mohammad Usman
 
Exploring Search Engines and their usage online
Exploring Search Engines and their usage onlineExploring Search Engines and their usage online
Exploring Search Engines and their usage online
Mohammad Usman
 
Web Technologies Types available on the internet
Web Technologies Types available on the internetWeb Technologies Types available on the internet
Web Technologies Types available on the internet
Mohammad Usman
 
AI open tools for Research.pptx
AI open tools for Research.pptxAI open tools for Research.pptx
AI open tools for Research.pptx
Mohammad Usman
 
Open AI Tools for Data Analytics
Open AI Tools for Data AnalyticsOpen AI Tools for Data Analytics
Open AI Tools for Data Analytics
Mohammad Usman
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Mohammad Usman
 
Object oriented programming with c++
Object oriented programming with c++Object oriented programming with c++
Object oriented programming with c++
Mohammad Usman
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
Career counselling banner
Career counselling bannerCareer counselling banner
Career counselling banner
Mohammad Usman
 
Literacy for or_against_the_poor_seminar
Literacy for or_against_the_poor_seminarLiteracy for or_against_the_poor_seminar
Literacy for or_against_the_poor_seminar
Mohammad Usman
 
Ad

Recently uploaded (20)

Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Ad

Functions in Python and its types for beginners

  • 2. Function • A function is a relationship or mapping between one or more inputs and a set of outputs. In mathematics, a function is typically represented like this: • Here, f is a function that operates on the inputs x and y. The output of the function is z. However, programming functions are much more generalized and versatile than this mathematical definition. In fact, appropriate function definition and use is so critical to proper software development that virtually all modern programming languages support both built-in and user-defined functions. • In programming, a function is a self-contained block of code that encapsulates a specific task or related group of tasks.
  • 3. The Importance of Python Functions Virtually all programming languages used today support a form of user-defined functions, although they aren’t always called functions. In other languages, you may see them referred to as one of the following: • Subroutines • Procedures • Methods • Subprograms
  • 5. Types of function • There are three types of functions in Python: • Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to print an object to the terminal,… You can find an overview with more of these functions here. • User-Defined Functions (UDFs), which are functions that users create to help them out; And • Anonymous functions, which are also called lambda functions because they are not declared with the standard def keyword.
  • 6. Functions vs. methods • A method refers to a function which is part of a class. You access it with an instance or object of the class. A function doesn’t have this restriction: it just refers to a standalone function. This means that all methods are functions, but not all functions are methods.
  • 7. Parameters vs. arguments • Parameters are the names used when defining a function or a method, and into which arguments will be mapped. In other words, arguments are the things which are supplied to any function or method call, while the function or method code refers to the arguments by their parameter names.
  • 8. User-Defined Functions (UDFs) • The four steps to defining a function in Python are the following: • Use the keyword def to declare the function and follow this up with the function name. • Add parameters to the function: they should be within the parentheses of the function. End your line with a colon. • Add statements that the functions should execute. • End your function with a return statement if the function should output something. Without the return statement, your function will return an object None.
  • 10. Component Meaning def The keyword that informs Python that a function is being defined <function_name> A valid Python identifier that names the function <parameters> An optional, comma-separated list of parameters that may be passed to the function : Punctuation that denotes the end of the Python function header (the name and
  • 11. def hello(): name = str(input("Enter your name: ")) if name: print ("Hello " + str(name)) else: print("Hello World") return hello()
  • 12. Argument Passing Positional Arguments • The most straightforward way to pass arguments to a Python function is with positional arguments (also called required arguments). In the function definition, you specify a comma- separated list of parameters inside the parentheses: >>> def f(qty, item, price): ... print(f'{qty} {item} cost ${price:.2f}') ... >>> f(6, 'bananas', 1.74) 6 bananas cost $1.74
  • 13. • Keyword Arguments If you want to make sure that you call all the parameters in the right order, you can use the keyword arguments in your function call. You use these to identify the arguments by their parameter name. >>> f(qty=6, item='bananas', price=1.74) 6 bananas cost $1.74 Using keyword arguments lifts the restriction on argument order. Each keyword argument explicitly designates a specific parameter by name, so you can specify them in any order and Python will still know which argument goes with which parameter:
  • 14. • Default Parameters • If a parameter specified in a Python function definition has the form <name>=<value>, then <value> becomes a default value for that parameter. Parameters defined this way are referred to as default or optional parameters. >>> def f(qty=6, item='bananas', price=1.74): ... print(f'{qty} {item} cost ${price:.2f}') ...
  • 15. >>> f(4, 'apples', 2.24) 4 apples cost $2.24 >>> f(4, 'apples') 4 apples cost $1.74 >>> f(4) 4 bananas cost $1.74 >>> f() 6 bananas cost $1.74 >>> f(item='kumquats', qty=9) 9 kumquats cost $1.74 >>> f(price=2.29) 6 bananas cost $2.29
  • 18. • Modular programming refers to the process of breaking a large, unwieldy programming task into separate, smaller, more manageable subtasks or modules. Individual modules can then be cobbled together like building blocks to create a larger application. • There are several advantages to modularizing code in a large application: Simplicity: Rather than focusing on the entire problem at hand, a module typically focuses on one relatively small portion of the problem. If you’re working on a single module, you’ll have a smaller problem domain to wrap your head around. This makes development easier and less error-prone.
  • 19. • Maintainability: Modules are typically designed so that they enforce logical boundaries between different problem domains. If modules are written in a way that minimizes interdependency, there is decreased likelihood that modifications to a single module will have an impact on other parts of the program. (You may even be able to make changes to a module without having any knowledge of the application outside that module.) This makes it more viable for a team of many programmers to work collaboratively on a large application. • Reusability: Functionality defined in a single module can be easily reused (through an appropriately defined interface) by other parts of the application. This eliminates the need to duplicate code. • Scoping: Modules typically define a separate namespace, which helps avoid collisions between identifiers in different areas of a program.
  • 20. Python Modules: • There are three different ways to define a module in Python: • A module can be written in Python itself. • A module can be written in C and loaded dynamically at run- time, like the re (regular expression) module. • A built-in module is intrinsically contained in the interpreter, like the itertools module.
  • 21. The import Statement • Module contents are made available to the caller with the import statement. The import statement takes many different forms, shown below. import <module_name> The simplest form is the one already shown above: import <module_name>
  • 22. from <module_name> import <name(s)> • An alternate form of the import statement allows individual objects from the module to be imported directly into the caller’s symbol table: • from <module_name> import <name(s)>