Movatterモバイル変換


[0]ホーム

URL:


1,722 views

Python Programming Essentials - M17 - Functions

The document discusses the basics of functions in Python, including what a function is, the advantages of using functions, how to define and call functions, and how to use parameters, return values, global variables, default arguments, keyword arguments, and docstrings when working with functions. Key points covered include how functions allow code reuse and decomposition of complex problems, how to define a function using the def keyword, how to call a defined function by name, and how docstrings provide documentation for functions and other objects.

Embed presentation

http://www.skillbrew.com/SkillbrewTalent brewed by theindustry itselfFunctions in PythonPavan Verma@YinYangPavan1Founder, P3 InfoTech Solutions Pvt. Ltd.Python Programming Essentials
© SkillBrew http://skillbrew.comWhat is a functionA function is a block of organized, reusable codethat is used to perform a single, related action2
© SkillBrew http://skillbrew.comAdvantages of using functions3Reusability. Reducingduplication of codeDecomposingcomplex problemsinto simpler piecesAbstraction Cleaner code
© SkillBrew http://skillbrew.comTypes of functionsTypes ofFunctionsBuilt-inFunctionsUser DefinedFunctions4
© SkillBrew http://skillbrew.comDefining a function5def functionName():# do somethingdef printList():num_list = range(3)print num_list1. def keyword is used to define a function2. def keyword is followed by a function name3. Function name is followed by parenthesis ()4. After this a block of python statements
© SkillBrew http://skillbrew.comCalling a Function6def printList():num_list = range(3)print num_listprintList()Output:[0, 1, 2]To call a function, we specify the function namewith the round bracketsCall to function
© SkillBrew http://skillbrew.comreturn keyword7def printList():num_list = range(3)return num_listmy_list = printList()print my_listOutput:[0, 1, 2]1. The return keyword isused to return valuesfrom a function2. A function implicitlyreturns None by defaulteven if you don’t usereturn keyword
© SkillBrew http://skillbrew.comParameterized functions8def printList(upper_limit):num_list = range(upper_limit)print "list: %s" % num_listprintList(5)printList(2)Output:list: [0, 1, 2, 3, 4]list: [0, 1]1. Names given in thefunction definitionare calledparameters2. The values yousupply in thefunction call arecalledarguments
© SkillBrew http://skillbrew.comDefault arguments9def printList(upper_limit=4):print "upper limit: %d" % upper_limitnum_list = range(upper_limit)print "list: %s" % num_listprintList(5)printList()Output:upper limit: 5list: [0, 1, 2, 3, 4]upper limit: 4list: [0, 1, 2, 3]value 41. When function is calledwithout any arguments defaultvalue is used2. During a function call ifargument is passed then thepassed value is used
© SkillBrew http://skillbrew.comDefault arguments (2)10A non-default argument may not follow defaultarguments while defining a functiondef printList(upper_limit=4, step):
© SkillBrew http://skillbrew.comKeyword arguments11def printList(upper_limit, step=1):print "upper limit: %d" % upper_limitnum_list = range(0, upper_limit, step)print "list: %s" % num_listprintList(upper_limit=5, step=2)Output:upper limit: 5list: [0, 2, 4]range() function has two variations:1.range(stop)2.range(start, stop[, step])
© SkillBrew http://skillbrew.comKeyword arguments (2)12printList(step=2, upper_limit=5)printList(upper_limit=5, step=2)Advantages of using keyword argumentsUsing the function is easier since you don’t have to worryabout or remember the order of the arguments
© SkillBrew http://skillbrew.comKeyword arguments (3)13You can give values to only those parameters which youwant, provided that the other parameters have defaultargument valueprintList(upper_limit=5)
© SkillBrew http://skillbrew.comKeyword arguments (4)14A non-keyword argument cannot follow keywordarguments while calling a functionprintList(upper_limit=4, 10)
© SkillBrew http://skillbrew.comglobal variables15counter = 10def printVar():print counterprintVar()print "counter: %d" % counterOutput:10counter: 10Variable defined outside a function or class is aglobal variablecounter is aglobal variable
© SkillBrew http://skillbrew.comglobal variables (2)16counter = 10def printVar():counter = 20print "Counter in: %d" % counterprintVar()print "Counter out: %d" % counterOutput:Counter in: 20Counter out: 10counter in function definition islocal variable tied to function’snamespaceHence the value of globalcounter does not gets modified
© SkillBrew http://skillbrew.comglobal variables (3)17counter = 10def printVar():global countercounter = 20print "Counter in: %d" % counterprintVar()print "Counter out: %d" % counterOutput:Counter in: 20Counter out: 20In order to use the globalcounter variable inside the functionyou have to explicitly tell python to useglobal variable using global keyword
© SkillBrew http://skillbrew.comdocstrings18def add(x, y):""" Return the sum of inputs x, y"""return x + yprint add.__doc__Python documentation strings (or docstrings) provide aconvenient way of associating documentation with Pythonmodules, functions, classes, and methodsdocstringAccess a docstring usingobject.__doc__
© SkillBrew http://skillbrew.comSummary What is a function Advantages of usingfunctions Defining a function Calling a function return keyword19 Parameterized functions Default arguments Keyword arguments global variables docstrings
© SkillBrew http://skillbrew.comResources Default argumentshttp://www.ibiblio.org/g2swap/byteofpython/read/default-argument-values.html Keyword argumentshttp://www.ibiblio.org/g2swap/byteofpython/read/keyword-arguments.html return keywordhttp://www.ibiblio.org/g2swap/byteofpython/read/return.html local variables http://www.ibiblio.org/g2swap/byteofpython/read/local-variables.html Docstringshttp://www.ibiblio.org/g2swap/byteofpython/read/docstrings.html20
21

Recommended

PPTX
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
PPTX
Python Programming Essentials - M31 - PEP 8
PPTX
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
PPT
C++ programming
PPTX
Python Programming Essentials - M35 - Iterators & Generators
PPTX
Function in c program
PPTX
Python programming workshop session 4
DOCX
Maharishi University of Management (MSc Computer Science test questions)
PPTX
PPTX
This pointer
PDF
46630497 fun-pointer-1
PPT
Function overloading(C++)
PPT
PDF
Python Functions (PyAtl Beginners Night)
PDF
仕事で使うF#
PPT
Unit 6 pointers
PPT
Fp201 unit5 1
PDF
From object oriented to functional domain modeling
PDF
Chapter 1 Basic Programming (Python Programming Lecture)
PPTX
Function in c program
PDF
Laziness, trampolines, monoids and other functional amenities: this is not yo...
PPTX
Functions in c language
PPT
FP 201 - Unit 3 Part 2
PDF
OOP and FP - Become a Better Programmer
PPT
RECURSION IN C
 
PPTX
Python programming
PPT
Simple Java Programs
PPTX
JNTUK python programming python unit 3.pptx
PPT
Powerpoint presentation for Python Functions

More Related Content

PPTX
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
PPTX
Python Programming Essentials - M31 - PEP 8
PPTX
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
PPT
C++ programming
PPTX
Python Programming Essentials - M35 - Iterators & Generators
PPTX
Function in c program
PPTX
Python programming workshop session 4
DOCX
Maharishi University of Management (MSc Computer Science test questions)
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
C++ programming
Python Programming Essentials - M35 - Iterators & Generators
Function in c program
Python programming workshop session 4
Maharishi University of Management (MSc Computer Science test questions)

What's hot

PPTX
PPTX
This pointer
PDF
46630497 fun-pointer-1
PPT
Function overloading(C++)
PPT
PDF
Python Functions (PyAtl Beginners Night)
PDF
仕事で使うF#
PPT
Unit 6 pointers
PPT
Fp201 unit5 1
PDF
From object oriented to functional domain modeling
PDF
Chapter 1 Basic Programming (Python Programming Lecture)
PPTX
Function in c program
PDF
Laziness, trampolines, monoids and other functional amenities: this is not yo...
PPTX
Functions in c language
PPT
FP 201 - Unit 3 Part 2
PDF
OOP and FP - Become a Better Programmer
PPT
RECURSION IN C
 
PPTX
Python programming
PPT
Simple Java Programs
This pointer
46630497 fun-pointer-1
Function overloading(C++)
Python Functions (PyAtl Beginners Night)
仕事で使うF#
Unit 6 pointers
Fp201 unit5 1
From object oriented to functional domain modeling
Chapter 1 Basic Programming (Python Programming Lecture)
Function in c program
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Functions in c language
FP 201 - Unit 3 Part 2
OOP and FP - Become a Better Programmer
RECURSION IN C
 
Python programming
Simple Java Programs

Similar to Python Programming Essentials - M17 - Functions

PPTX
JNTUK python programming python unit 3.pptx
PPT
Powerpoint presentation for Python Functions
PPT
python slides introduction interrupt.ppt
PDF
functions notes.pdf python functions and opp
PPT
functions _
PPTX
Functions in Python Programming Language
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPT
Python programming variables and comment
PPTX
UNIT 3 python.pptx
PPTX
Python Functions.pptx
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPTX
PYTHON_FUNCTIONS in Detail user defined and Built In
PPTX
Python programming - Functions and list and tuples
PDF
functions- best.pdf
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPT
functions modules and exceptions handlings.ppt
PPTX
Python_Functions_Unit1.pptx
PPTX
Python for Data Science function third module ppt.pptx
 
PPTX
Decided to go to the 65 and the value of the number
JNTUK python programming python unit 3.pptx
Powerpoint presentation for Python Functions
python slides introduction interrupt.ppt
functions notes.pdf python functions and opp
functions _
Functions in Python Programming Language
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Python programming variables and comment
UNIT 3 python.pptx
Python Functions.pptx
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PYTHON_FUNCTIONS in Detail user defined and Built In
Python programming - Functions and list and tuples
functions- best.pdf
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
functions modules and exceptions handlings.ppt
Python_Functions_Unit1.pptx
Python for Data Science function third module ppt.pptx
 
Decided to go to the 65 and the value of the number

More from P3 InfoTech Solutions Pvt. Ltd.

PPTX
Python Programming Essentials - M44 - Overview of Web Development
PPTX
Python Programming Essentials - M40 - Invoking External Programs
PPTX
Python Programming Essentials - M39 - Unit Testing
PPTX
Python Programming Essentials - M34 - List Comprehensions
PPTX
Python Programming Essentials - M29 - Python Interpreter and Files
PPTX
Python Programming Essentials - M28 - Debugging with pdb
PPTX
Python Programming Essentials - M27 - Logging module
PPTX
Python Programming Essentials - M25 - os and sys modules
PPTX
Python Programming Essentials - M24 - math module
PPTX
Python Programming Essentials - M23 - datetime module
PPTX
Python Programming Essentials - M22 - File Operations
PPTX
Python Programming Essentials - M21 - Exception Handling
PPTX
Python Programming Essentials - M20 - Classes and Objects
PPTX
Python Programming Essentials - M18 - Modules and Packages
PPTX
Python Programming Essentials - M16 - Control Flow Statements and Loops
PPTX
Python Programming Essentials - M15 - References
PPTX
Python Programming Essentials - M14 - Dictionaries
PPTX
Python Programming Essentials - M13 - Tuples
PPTX
Python Programming Essentials - M12 - Lists
PPTX
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M24 - math module
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M15 - References
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M13 - Tuples
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M11 - Comparison and Logical Operators

Recently uploaded

PDF
"DISC as GPS for team leaders: how to lead a team from storming to performing...
 
PPTX
Leon Brands - Intro to GPU Occlusion (Graphics Programming Conference 2024)
PPTX
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
PDF
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
PDF
[BDD 2025 - Mobile Development] Exploring Apple’s On-Device FoundationModels
PPTX
MuleSoft AI Series : Introduction to MCP
PDF
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
PPTX
Connecting the unconnectable: Exploring LoRaWAN for IoT
PDF
[BDD 2025 - Full-Stack Development] Agentic AI Architecture: Redefining Syste...
PDF
The Evolving Role of the CEO in the Age of AI
PPTX
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
PDF
[BDD 2025 - Full-Stack Development] PHP in AI Age: The Laravel Way. (Rizqy Hi...
PDF
Open Source Post-Quantum Cryptography - Matt Caswell
PDF
DUBAI IT MODERNIZATION WITH AZURE MANAGED SERVICES.pdf
PPTX
kernel PPT (Explanation of Windows Kernal).pptx
PDF
Cybersecurity Prevention and Detection: Unit 2
PPTX
Support, Monitoring, Continuous Improvement & Scaling Agentic Automation [3/3]
PDF
Top Crypto Supers 15th Report November 2025
PDF
Dev Dives: Build smarter agents with UiPath Agent Builder
PDF
Mulesoft Meetup Online Portuguese: MCP e IA
"DISC as GPS for team leaders: how to lead a team from storming to performing...
 
Leon Brands - Intro to GPU Occlusion (Graphics Programming Conference 2024)
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
[BDD 2025 - Mobile Development] Exploring Apple’s On-Device FoundationModels
MuleSoft AI Series : Introduction to MCP
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
Connecting the unconnectable: Exploring LoRaWAN for IoT
[BDD 2025 - Full-Stack Development] Agentic AI Architecture: Redefining Syste...
The Evolving Role of the CEO in the Age of AI
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
[BDD 2025 - Full-Stack Development] PHP in AI Age: The Laravel Way. (Rizqy Hi...
Open Source Post-Quantum Cryptography - Matt Caswell
DUBAI IT MODERNIZATION WITH AZURE MANAGED SERVICES.pdf
kernel PPT (Explanation of Windows Kernal).pptx
Cybersecurity Prevention and Detection: Unit 2
Support, Monitoring, Continuous Improvement & Scaling Agentic Automation [3/3]
Top Crypto Supers 15th Report November 2025
Dev Dives: Build smarter agents with UiPath Agent Builder
Mulesoft Meetup Online Portuguese: MCP e IA

Python Programming Essentials - M17 - Functions

  • 1.
    http://www.skillbrew.com/SkillbrewTalent brewed bytheindustry itselfFunctions in PythonPavan Verma@YinYangPavan1Founder, P3 InfoTech Solutions Pvt. Ltd.Python Programming Essentials
  • 2.
    © SkillBrew http://skillbrew.comWhatis a functionA function is a block of organized, reusable codethat is used to perform a single, related action2
  • 3.
    © SkillBrew http://skillbrew.comAdvantagesof using functions3Reusability. Reducingduplication of codeDecomposingcomplex problemsinto simpler piecesAbstraction Cleaner code
  • 4.
    © SkillBrew http://skillbrew.comTypesof functionsTypes ofFunctionsBuilt-inFunctionsUser DefinedFunctions4
  • 5.
    © SkillBrew http://skillbrew.comDefininga function5def functionName():# do somethingdef printList():num_list = range(3)print num_list1. def keyword is used to define a function2. def keyword is followed by a function name3. Function name is followed by parenthesis ()4. After this a block of python statements
  • 6.
    © SkillBrew http://skillbrew.comCallinga Function6def printList():num_list = range(3)print num_listprintList()Output:[0, 1, 2]To call a function, we specify the function namewith the round bracketsCall to function
  • 7.
    © SkillBrew http://skillbrew.comreturnkeyword7def printList():num_list = range(3)return num_listmy_list = printList()print my_listOutput:[0, 1, 2]1. The return keyword isused to return valuesfrom a function2. A function implicitlyreturns None by defaulteven if you don’t usereturn keyword
  • 8.
    © SkillBrew http://skillbrew.comParameterizedfunctions8def printList(upper_limit):num_list = range(upper_limit)print "list: %s" % num_listprintList(5)printList(2)Output:list: [0, 1, 2, 3, 4]list: [0, 1]1. Names given in thefunction definitionare calledparameters2. The values yousupply in thefunction call arecalledarguments
  • 9.
    © SkillBrew http://skillbrew.comDefaultarguments9def printList(upper_limit=4):print "upper limit: %d" % upper_limitnum_list = range(upper_limit)print "list: %s" % num_listprintList(5)printList()Output:upper limit: 5list: [0, 1, 2, 3, 4]upper limit: 4list: [0, 1, 2, 3]value 41. When function is calledwithout any arguments defaultvalue is used2. During a function call ifargument is passed then thepassed value is used
  • 10.
    © SkillBrew http://skillbrew.comDefaultarguments (2)10A non-default argument may not follow defaultarguments while defining a functiondef printList(upper_limit=4, step):
  • 11.
    © SkillBrew http://skillbrew.comKeywordarguments11def printList(upper_limit, step=1):print "upper limit: %d" % upper_limitnum_list = range(0, upper_limit, step)print "list: %s" % num_listprintList(upper_limit=5, step=2)Output:upper limit: 5list: [0, 2, 4]range() function has two variations:1.range(stop)2.range(start, stop[, step])
  • 12.
    © SkillBrew http://skillbrew.comKeywordarguments (2)12printList(step=2, upper_limit=5)printList(upper_limit=5, step=2)Advantages of using keyword argumentsUsing the function is easier since you don’t have to worryabout or remember the order of the arguments
  • 13.
    © SkillBrew http://skillbrew.comKeywordarguments (3)13You can give values to only those parameters which youwant, provided that the other parameters have defaultargument valueprintList(upper_limit=5)
  • 14.
    © SkillBrew http://skillbrew.comKeywordarguments (4)14A non-keyword argument cannot follow keywordarguments while calling a functionprintList(upper_limit=4, 10)
  • 15.
    © SkillBrew http://skillbrew.comglobalvariables15counter = 10def printVar():print counterprintVar()print "counter: %d" % counterOutput:10counter: 10Variable defined outside a function or class is aglobal variablecounter is aglobal variable
  • 16.
    © SkillBrew http://skillbrew.comglobalvariables (2)16counter = 10def printVar():counter = 20print "Counter in: %d" % counterprintVar()print "Counter out: %d" % counterOutput:Counter in: 20Counter out: 10counter in function definition islocal variable tied to function’snamespaceHence the value of globalcounter does not gets modified
  • 17.
    © SkillBrew http://skillbrew.comglobalvariables (3)17counter = 10def printVar():global countercounter = 20print "Counter in: %d" % counterprintVar()print "Counter out: %d" % counterOutput:Counter in: 20Counter out: 20In order to use the globalcounter variable inside the functionyou have to explicitly tell python to useglobal variable using global keyword
  • 18.
    © SkillBrew http://skillbrew.comdocstrings18defadd(x, y):""" Return the sum of inputs x, y"""return x + yprint add.__doc__Python documentation strings (or docstrings) provide aconvenient way of associating documentation with Pythonmodules, functions, classes, and methodsdocstringAccess a docstring usingobject.__doc__
  • 19.
    © SkillBrew http://skillbrew.comSummaryWhat is a function Advantages of usingfunctions Defining a function Calling a function return keyword19 Parameterized functions Default arguments Keyword arguments global variables docstrings
  • 20.
    © SkillBrew http://skillbrew.comResourcesDefault argumentshttp://www.ibiblio.org/g2swap/byteofpython/read/default-argument-values.html Keyword argumentshttp://www.ibiblio.org/g2swap/byteofpython/read/keyword-arguments.html return keywordhttp://www.ibiblio.org/g2swap/byteofpython/read/return.html local variables http://www.ibiblio.org/g2swap/byteofpython/read/local-variables.html Docstringshttp://www.ibiblio.org/g2swap/byteofpython/read/docstrings.html20
  • 21.

[8]ページ先頭

©2009-2025 Movatter.jp