SlideShare a Scribd company logo
Python Functions
What is a function in Python?
• Is a group of related statements that perform
a specific task
• Help break our program into smaller and
modular chunks
• As program grows larger and larger, functions
make it more organized and manageable
• Furthermore, it avoids repetition and makes
code reusable
Syntax of Function
Example of a function
Docstring
The return statement
How Function works in Python?
Scope and Lifetime of variables
• Scope of a variable is the portion of a program where
the variable is recognized
• Parameters and variables defined inside a function is
not visible from outside. Hence, they have a local
scope.
• Lifetime of a variable is the period throughout which
the variable exits in the memory.
• The lifetime of variables inside a function is as long as
the function executes.
• They are destroyed once we return from the function.
Hence, a function does not remember the value of a
variable from its previous calls.
Example
Types of Functions
• Can be divided into the following two types:
– Built-in functions: Functions that are built into
Python
– User-defined functions: Functions defined by the
users themselves
Arguments
Python Default Arguments
Python Keyword Arguments
Python Arbitrary Arguments
Python Recursion
• What is recursion in Python?
• Python Recursive Function
• Advantages of Recursion
• Disadvantages of Recursion
What is recursion in Python?
• Recursion is the process of defining something
in terms of itself
• A physical world example would be to place
two parallel mirrors facing each other
• Any object in between them would be
reflected recursively
Python Recursive Function
Functions in Python
Advantages of Recursion
• Make the code look clean and elegant
• A complex task can be broken down into
simpler sub-problems using recursion
Disadvantages of Recursion
• Sometimes the logic behind recursion is hard
to follow through
• Recursive calls are expensive (inefficient) as
they take up a lot of memory and time
• Recursive functions are hard to debug
Python Anonymous/Lambda Function
• What are lambda functions in Python?
• How to use lambda Functions in Python?
– Syntax of Lambda Function in python
– Example of Lambda Function in python
– Use of Lambda Function in python
What are lambda functions in Python?
• In Python, anonymous function is a function
that is defined without a name.
• While normal functions are defined using the
def keyword, in Python anonymous functions
are defined using the lambda keyword.
• Hence, anonymous functions are also called
lambda functions.
How to use lambda Functions in
Python?
• Syntax of Lambda Function in python
Example of Lambda Function in python
Use of Lambda Function in python
Functions in Python
Python Global, Local and Nonlocal
variables
• Global Variables in Python
• Local Variables in Python
• Global and Local Variables Together
• Nonlocal Variables in Python
Global Variables in Python
Functions in Python
Local Variables in Python
Global and Local Variables Together
Functions in Python
Nonlocal Variables in Python
Python Global Keyword
• Python global Keyword
– Rules of global Keyword
– Use of global Keyword (With Example)
• Global Variables Across Python Modules
• Global in Nested Functions in Python
Python global Keyword
• The basic rules for global keyword in Python are:
– When we create a variable inside a function, it’s local
by default
– When we define a variable outside of a function, it’s
global by default. We don’t have to use global
keyword.
– We use global keyword to read and write a global
variable inside a function.
– Use of global keyword outside a function has no effect
Functions in Python
Functions in Python
Functions in Python
Global Variables Across Python
Modules
Functions in Python
Global in Nested Functions
Python Modules
• What are modules in Python?
• How to import modules in Python?
– Python import statement
– Import with renaming
– Python from...import statement
– Import all names
• Python Module Search Path
• Reloading a module
• The dir() built-in function
What are modules in Python?
• File containing Python statements and
definitions
– Example: example.py, is called a module
• Use to break down large programs into small
manageable and organized files.
• Provide reusability of code
• Can define our most used functions in a
module and import it, instead of copying their
definitions into different programs
How to import modules in Python?
• Python import statement
• Import with renaming
• Python from...import statement
• Import all names
Python import statement
Import with renaming
Python from...import statement
Import all names
Python Module Search Path
• While importing a module, Python looks at
several places.
• Interpreter first looks for a built-in module then
(if not found) into a list of directories defined in
sys.path.
• The search is in this order.
– The current directory.
– PYTHONPATH (an environment variable with a list of
directory).
– The installation-dependent default directory.
Functions in Python
Reloading a module
The dir() built-in function
• We can use the dir() function to find out
names that are defined inside a module.
Functions in Python
Python Package
• What are packages?
• Importing module from a package
What are packages?
• We don't usually store all of our files in our
computer in the same location.
• Similar files are kept in the same directory, for
example, we may keep all the songs in the
"music" directory.
• Analogous to this, Python has packages for
directories and modules for files.
• As our application program grows larger in size
with a lot of modules, we place similar modules
in one package and different modules in different
packages.
• Similar, as a directory can contain sub-directories
and files, a Python package can have sub-
packages and modules.
• A directory must contain a file named __init__.py
in order for Python to consider it as a package.
• This file can be left empty but we generally place
the initialization code for that package in this file
Functions in Python
Importing module from a package
• We can import modules from packages using the
dot (.) operator.
• For example, if we want to import the start
module in the above example, it is done as
follows.
– import Game.Level.start
• Now if this module contains a function named
select_difficulty(), we must use the full name to
reference it.
– Game.Level.start.select_difficulty(2)
• We can also import the module without the
package prefix as follows
– from Game.Level import start
• We can now call the function simply as
follows.
– start.select_difficulty(2)
• Yet another way of importing just the required
function (or class or variable) form a module
within a package would be as follows.
– from Game.Level.start import
select_difficulty
• Now we can directly call this function.
– select_difficulty(2)
Thank You !

More Related Content

What's hot (20)

PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PPTX
File handling in Python
Megha V
 
PDF
Namespaces
Sangeetha S
 
PPTX
Functions in Python
Shakti Singh Rathore
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PPTX
Packages In Python Tutorial
Simplilearn
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PDF
Variables & Data Types In Python | Edureka
Edureka!
 
PDF
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
PPTX
Data types in python
RaginiJain21
 
PDF
Python set
Mohammed Sikander
 
PDF
Strings in python
Prabhakaran V M
 
PPTX
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Datastructures in python
hydpy
 
PPTX
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
PDF
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
File handling in Python
Megha V
 
Namespaces
Sangeetha S
 
Functions in Python
Shakti Singh Rathore
 
Chapter 05 classes and objects
Praveen M Jigajinni
 
Modules and packages in python
TMARAGATHAM
 
Packages In Python Tutorial
Simplilearn
 
Regular expressions in Python
Sujith Kumar
 
Python: Modules and Packages
Damian T. Gordon
 
Variables & Data Types In Python | Edureka
Edureka!
 
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Data types in python
RaginiJain21
 
Python set
Mohammed Sikander
 
Strings in python
Prabhakaran V M
 
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Datastructures in python
hydpy
 
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 

Similar to Functions in Python (20)

PPTX
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
 
PPTX
Functions_in_Python.pptx
krushnaraj1
 
PDF
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
 
PPTX
Functions and Modules.pptx
Ashwini Raut
 
PPTX
Functions in Python Syntax and working .
tarunsharmaug23
 
PDF
Unit-2 Introduction of Modules and Packages.pdf
Harsha Patil
 
PPTX
Chapter - 4.pptx
MikialeTesfamariam
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
Python Modules, executing modules as script.pptx
Singamvineela
 
PPTX
Decided to go to the 65 and the value of the number
harshoberoi2050
 
PDF
ch 2. Python module
Prof .Pragati Khade
 
PDF
functions notes.pdf python functions and opp
KirtiGarg71
 
PPTX
UNIT 3 python.pptx
TKSanthoshRao
 
PDF
Functions and modules in python
Karin Lagesen
 
PPT
jb_Modules_in_Python.ppt
loliktry
 
PPT
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
paurushsinhad
 
PPT
Python modules
Shanmugapriya Dineshbabu
 
PPTX
_Python_ Functions _and_ Libraries_.pptx
yaramahsoob
 
PPTX
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
 
Functions_in_Python.pptx
krushnaraj1
 
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
 
Functions and Modules.pptx
Ashwini Raut
 
Functions in Python Syntax and working .
tarunsharmaug23
 
Unit-2 Introduction of Modules and Packages.pdf
Harsha Patil
 
Chapter - 4.pptx
MikialeTesfamariam
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Python Modules, executing modules as script.pptx
Singamvineela
 
Decided to go to the 65 and the value of the number
harshoberoi2050
 
ch 2. Python module
Prof .Pragati Khade
 
functions notes.pdf python functions and opp
KirtiGarg71
 
UNIT 3 python.pptx
TKSanthoshRao
 
Functions and modules in python
Karin Lagesen
 
jb_Modules_in_Python.ppt
loliktry
 
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
paurushsinhad
 
Python modules
Shanmugapriya Dineshbabu
 
_Python_ Functions _and_ Libraries_.pptx
yaramahsoob
 
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Ad

More from Kamal Acharya (20)

PPTX
Programming the basic computer
Kamal Acharya
 
PPTX
Computer Arithmetic
Kamal Acharya
 
PPTX
Introduction to Computer Security
Kamal Acharya
 
PPTX
Session and Cookies
Kamal Acharya
 
PPTX
Functions in php
Kamal Acharya
 
PPTX
Web forms in php
Kamal Acharya
 
PPTX
Making decision and repeating in PHP
Kamal Acharya
 
PPTX
Working with arrays in php
Kamal Acharya
 
PPTX
Text and Numbers (Data Types)in PHP
Kamal Acharya
 
PPTX
Introduction to PHP
Kamal Acharya
 
PPTX
Capacity Planning of Data Warehousing
Kamal Acharya
 
PPTX
Data Warehousing
Kamal Acharya
 
PPTX
Search Engines
Kamal Acharya
 
PPTX
Web Mining
Kamal Acharya
 
PPTX
Information Privacy and Data Mining
Kamal Acharya
 
PPTX
Cluster Analysis
Kamal Acharya
 
PPTX
Association Analysis in Data Mining
Kamal Acharya
 
PPTX
Classification techniques in data mining
Kamal Acharya
 
PPTX
Data Preprocessing
Kamal Acharya
 
PPTX
Introduction to Data Mining and Data Warehousing
Kamal Acharya
 
Programming the basic computer
Kamal Acharya
 
Computer Arithmetic
Kamal Acharya
 
Introduction to Computer Security
Kamal Acharya
 
Session and Cookies
Kamal Acharya
 
Functions in php
Kamal Acharya
 
Web forms in php
Kamal Acharya
 
Making decision and repeating in PHP
Kamal Acharya
 
Working with arrays in php
Kamal Acharya
 
Text and Numbers (Data Types)in PHP
Kamal Acharya
 
Introduction to PHP
Kamal Acharya
 
Capacity Planning of Data Warehousing
Kamal Acharya
 
Data Warehousing
Kamal Acharya
 
Search Engines
Kamal Acharya
 
Web Mining
Kamal Acharya
 
Information Privacy and Data Mining
Kamal Acharya
 
Cluster Analysis
Kamal Acharya
 
Association Analysis in Data Mining
Kamal Acharya
 
Classification techniques in data mining
Kamal Acharya
 
Data Preprocessing
Kamal Acharya
 
Introduction to Data Mining and Data Warehousing
Kamal Acharya
 
Ad

Recently uploaded (20)

PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PPTX
How to use _name_search() method in Odoo 18
Celine George
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PDF
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
PDF
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
DOCX
ANNOTATION on objective 10 on pmes 2022-2025
joviejanesegundo1
 
PPTX
How to Add New Item in CogMenu in Odoo 18
Celine George
 
PDF
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
PPTX
How to use grouped() method in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Martyrs of Ireland - who kept the faith of St. Patrick.pptx
Martin M Flynn
 
DOCX
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
PPTX
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PPTX
SYMPATHOMIMETICS[ADRENERGIC AGONISTS] pptx
saip95568
 
PPTX
Peer Teaching Observations During School Internship
AjayaMohanty7
 
PDF
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
PPT
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
DOCX
DLL english grade five goof for one week
FlordelynGonzales1
 
PDF
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
How to use _name_search() method in Odoo 18
Celine George
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
ANNOTATION on objective 10 on pmes 2022-2025
joviejanesegundo1
 
How to Add New Item in CogMenu in Odoo 18
Celine George
 
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
How to use grouped() method in Odoo 18 - Odoo Slides
Celine George
 
Martyrs of Ireland - who kept the faith of St. Patrick.pptx
Martin M Flynn
 
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
SYMPATHOMIMETICS[ADRENERGIC AGONISTS] pptx
saip95568
 
Peer Teaching Observations During School Internship
AjayaMohanty7
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
DLL english grade five goof for one week
FlordelynGonzales1
 
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 

Functions in Python

  • 2. What is a function in Python? • Is a group of related statements that perform a specific task • Help break our program into smaller and modular chunks • As program grows larger and larger, functions make it more organized and manageable • Furthermore, it avoids repetition and makes code reusable
  • 4. Example of a function
  • 7. How Function works in Python?
  • 8. Scope and Lifetime of variables • Scope of a variable is the portion of a program where the variable is recognized • Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope. • Lifetime of a variable is the period throughout which the variable exits in the memory. • The lifetime of variables inside a function is as long as the function executes. • They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.
  • 10. Types of Functions • Can be divided into the following two types: – Built-in functions: Functions that are built into Python – User-defined functions: Functions defined by the users themselves
  • 15. Python Recursion • What is recursion in Python? • Python Recursive Function • Advantages of Recursion • Disadvantages of Recursion
  • 16. What is recursion in Python? • Recursion is the process of defining something in terms of itself • A physical world example would be to place two parallel mirrors facing each other • Any object in between them would be reflected recursively
  • 19. Advantages of Recursion • Make the code look clean and elegant • A complex task can be broken down into simpler sub-problems using recursion
  • 20. Disadvantages of Recursion • Sometimes the logic behind recursion is hard to follow through • Recursive calls are expensive (inefficient) as they take up a lot of memory and time • Recursive functions are hard to debug
  • 21. Python Anonymous/Lambda Function • What are lambda functions in Python? • How to use lambda Functions in Python? – Syntax of Lambda Function in python – Example of Lambda Function in python – Use of Lambda Function in python
  • 22. What are lambda functions in Python? • In Python, anonymous function is a function that is defined without a name. • While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. • Hence, anonymous functions are also called lambda functions.
  • 23. How to use lambda Functions in Python? • Syntax of Lambda Function in python
  • 24. Example of Lambda Function in python
  • 25. Use of Lambda Function in python
  • 27. Python Global, Local and Nonlocal variables • Global Variables in Python • Local Variables in Python • Global and Local Variables Together • Nonlocal Variables in Python
  • 31. Global and Local Variables Together
  • 34. Python Global Keyword • Python global Keyword – Rules of global Keyword – Use of global Keyword (With Example) • Global Variables Across Python Modules • Global in Nested Functions in Python
  • 35. Python global Keyword • The basic rules for global keyword in Python are: – When we create a variable inside a function, it’s local by default – When we define a variable outside of a function, it’s global by default. We don’t have to use global keyword. – We use global keyword to read and write a global variable inside a function. – Use of global keyword outside a function has no effect
  • 39. Global Variables Across Python Modules
  • 41. Global in Nested Functions
  • 42. Python Modules • What are modules in Python? • How to import modules in Python? – Python import statement – Import with renaming – Python from...import statement – Import all names • Python Module Search Path • Reloading a module • The dir() built-in function
  • 43. What are modules in Python? • File containing Python statements and definitions – Example: example.py, is called a module • Use to break down large programs into small manageable and organized files. • Provide reusability of code • Can define our most used functions in a module and import it, instead of copying their definitions into different programs
  • 44. How to import modules in Python? • Python import statement • Import with renaming • Python from...import statement • Import all names
  • 49. Python Module Search Path • While importing a module, Python looks at several places. • Interpreter first looks for a built-in module then (if not found) into a list of directories defined in sys.path. • The search is in this order. – The current directory. – PYTHONPATH (an environment variable with a list of directory). – The installation-dependent default directory.
  • 52. The dir() built-in function • We can use the dir() function to find out names that are defined inside a module.
  • 54. Python Package • What are packages? • Importing module from a package
  • 55. What are packages? • We don't usually store all of our files in our computer in the same location. • Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory. • Analogous to this, Python has packages for directories and modules for files.
  • 56. • As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. • Similar, as a directory can contain sub-directories and files, a Python package can have sub- packages and modules. • A directory must contain a file named __init__.py in order for Python to consider it as a package. • This file can be left empty but we generally place the initialization code for that package in this file
  • 58. Importing module from a package • We can import modules from packages using the dot (.) operator. • For example, if we want to import the start module in the above example, it is done as follows. – import Game.Level.start • Now if this module contains a function named select_difficulty(), we must use the full name to reference it. – Game.Level.start.select_difficulty(2)
  • 59. • We can also import the module without the package prefix as follows – from Game.Level import start • We can now call the function simply as follows. – start.select_difficulty(2)
  • 60. • Yet another way of importing just the required function (or class or variable) form a module within a package would be as follows. – from Game.Level.start import select_difficulty • Now we can directly call this function. – select_difficulty(2)