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

More Related Content

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

What's hot

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

Similar to Python Programming Essentials - M17 - Functions

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

More from P3 InfoTech Solutions Pvt. Ltd.

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

Recently uploaded

PDF
Parallel Computing BCS702 Module notes of the vtu college 7th sem 4.pdf
PDF
[BDD 2025 - Full-Stack Development] The Modern Stack: Building Web & AI Appli...
PDF
Mulesoft Meetup Online Portuguese: MCP e IA
PDF
Transforming Content Operations in the Age of AI
PPTX
"Feelings versus facts: why metrics are more important than intuition", Igor ...
 
PDF
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
PDF
[BDD 2025 - Mobile Development] Mobile Engineer and Software Engineer: Are we...
PPTX
MuleSoft AI Series : Introduction to MCP
PDF
[BDD 2025 - Artificial Intelligence] Building AI Systems That Users (and Comp...
PDF
10 Best Automation QA Testing Software Tools in 2025.pdf
PDF
MuleSoft Meetup: Dreamforce'25 Tour- Vibing With AI & Agents.pdf
PDF
[BDD 2025 - Mobile Development] Crafting Immersive UI with E2E and AGSL Shade...
PDF
Open Source Post-Quantum Cryptography - Matt Caswell
PDF
Top Crypto Supers 15th Report November 2025
PDF
5 Common Supply Chain Attacks and How They Work | CyberPro Magazine
PDF
Transcript: The partnership effect: Libraries and publishers on collaborating...
PDF
Integrating AI with Meaningful Human Collaboration
PPTX
Connecting the unconnectable: Exploring LoRaWAN for IoT
PPTX
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
PDF
Cybersecurity Prevention and Detection: Unit 2
Parallel Computing BCS702 Module notes of the vtu college 7th sem 4.pdf
[BDD 2025 - Full-Stack Development] The Modern Stack: Building Web & AI Appli...
Mulesoft Meetup Online Portuguese: MCP e IA
Transforming Content Operations in the Age of AI
"Feelings versus facts: why metrics are more important than intuition", Igor ...
 
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
[BDD 2025 - Mobile Development] Mobile Engineer and Software Engineer: Are we...
MuleSoft AI Series : Introduction to MCP
[BDD 2025 - Artificial Intelligence] Building AI Systems That Users (and Comp...
10 Best Automation QA Testing Software Tools in 2025.pdf
MuleSoft Meetup: Dreamforce'25 Tour- Vibing With AI & Agents.pdf
[BDD 2025 - Mobile Development] Crafting Immersive UI with E2E and AGSL Shade...
Open Source Post-Quantum Cryptography - Matt Caswell
Top Crypto Supers 15th Report November 2025
5 Common Supply Chain Attacks and How They Work | CyberPro Magazine
Transcript: The partnership effect: Libraries and publishers on collaborating...
Integrating AI with Meaningful Human Collaboration
Connecting the unconnectable: Exploring LoRaWAN for IoT
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
Cybersecurity Prevention and Detection: Unit 2

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