SlideShare ist ein Scribd-Unternehmen logo
1 von 21
http://www.skillbrew.com
/SkillbrewTalent brewed by the
industry itself
Functions in Python
Pavan Verma
@YinYangPavan
1
Founder, P3 InfoTech Solutions Pvt. Ltd.
Python Programming Essentials
© SkillBrew http://skillbrew.com
What is a function
A function is a block of organized, reusable code
that is used to perform a single, related action
2
© SkillBrew http://skillbrew.com
Advantages of using functions
3
Reusability. Reducing
duplication of code
Decomposing
complex problems
into simpler pieces
Abstraction Cleaner code
© SkillBrew http://skillbrew.com
Types of functions
Types of
Functions
Built-in
Functions
User Defined
Functions
4
© SkillBrew http://skillbrew.com
Defining a function
5
def functionName():
# do something
def printList():
num_list = range(3)
print num_list
1. def keyword is used to define a function
2. def keyword is followed by a function name
3. Function name is followed by parenthesis ()
4. After this a block of python statements
© SkillBrew http://skillbrew.com
Calling a Function
6
def printList():
num_list = range(3)
print num_list
printList()
Output:
[0, 1, 2]
To call a function, we specify the function name
with the round brackets
Call to function
© SkillBrew http://skillbrew.com
return keyword
7
def printList():
num_list = range(3)
return num_list
my_list = printList()
print my_list
Output:
[0, 1, 2]
1. The return keyword is
used to return values
from a function
2. A function implicitly
returns None by default
even if you don’t use
return keyword
© SkillBrew http://skillbrew.com
Parameterized functions
8
def printList(upper_limit):
num_list = range(upper_limit)
print "list: %s" % num_list
printList(5)
printList(2)
Output:
list: [0, 1, 2, 3, 4]
list: [0, 1]
1. Names given in the
function definition
are called
parameters
2. The values you
supply in the
function call are
called
arguments
© SkillBrew http://skillbrew.com
Default arguments
9
def printList(upper_limit=4):
print "upper limit: %d" % upper_limit
num_list = range(upper_limit)
print "list: %s" % num_list
printList(5)
printList()
Output:
upper limit: 5
list: [0, 1, 2, 3, 4]
upper limit: 4
list: [0, 1, 2, 3]
value 4
1. When function is called
without any arguments default
value is used
2. During a function call if
argument is passed then the
passed value is used
© SkillBrew http://skillbrew.com
Default arguments (2)
10
A non-default argument may not follow default
arguments while defining a function
def printList(upper_limit=4, step):
© SkillBrew http://skillbrew.com
Keyword arguments
11
def printList(upper_limit, step=1):
print "upper limit: %d" % upper_limit
num_list = range(0, upper_limit, step)
print "list: %s" % num_list
printList(upper_limit=5, step=2)
Output:
upper limit: 5
list: [0, 2, 4]
range() function has two variations:
1.range(stop)
2.range(start, stop[, step])
© SkillBrew http://skillbrew.com
Keyword arguments (2)
12
printList(step=2, upper_limit=5)
printList(upper_limit=5, step=2)
Advantages of using keyword arguments
Using the function is easier since you don’t have to worry
about or remember the order of the arguments
© SkillBrew http://skillbrew.com
Keyword arguments (3)
13
You can give values to only those parameters which you
want, provided that the other parameters have default
argument value
printList(upper_limit=5)
© SkillBrew http://skillbrew.com
Keyword arguments (4)
14
A non-keyword argument cannot follow keyword
arguments while calling a function
printList(upper_limit=4, 10)
© SkillBrew http://skillbrew.com
global variables
15
counter = 10
def printVar():
print counter
printVar()
print "counter: %d" % counter
Output:
10
counter: 10
Variable defined outside a function or class is a
global variable
counter is a
global variable
© SkillBrew http://skillbrew.com
global variables (2)
16
counter = 10
def printVar():
counter = 20
print "Counter in: %d" % counter
printVar()
print "Counter out: %d" % counter
Output:
Counter in: 20
Counter out: 10
counter in function definition is
local variable tied to function’s
namespace
Hence the value of global
counter does not gets modified
© SkillBrew http://skillbrew.com
global variables (3)
17
counter = 10
def printVar():
global counter
counter = 20
print "Counter in: %d" % counter
printVar()
print "Counter out: %d" % counter
Output:
Counter in: 20
Counter out: 20
In order to use the global
counter variable inside the function
you have to explicitly tell python to use
global variable using global keyword
© SkillBrew http://skillbrew.com
docstrings
18
def add(x, y):
""" Return the sum of inputs x, y
"""
return x + y
print add.__doc__
Python documentation strings (or docstrings) provide a
convenient way of associating documentation with Python
modules, functions, classes, and methods
docstring
Access a docstring using
object.__doc__
© SkillBrew http://skillbrew.com
Summary
 What is a function
 Advantages of using
functions
 Defining a function
 Calling a function
 return keyword
19
 Parameterized functions
 Default arguments
 Keyword arguments
 global variables
 docstrings
© SkillBrew http://skillbrew.com
Resources
 Default arguments
http://www.ibiblio.org/g2swap/byteofpython/read/default-argument-
values.html
 Keyword arguments
http://www.ibiblio.org/g2swap/byteofpython/read/keyword-
arguments.html
 return keyword
http://www.ibiblio.org/g2swap/byteofpython/read/return.html
 local variables http://www.ibiblio.org/g2swap/byteofpython/read/local-
variables.html
 Docstrings
http://www.ibiblio.org/g2swap/byteofpython/read/docstrings.html
20
21

Weitere ähnliche Inhalte

Was ist angesagt?

46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)IoT Code Lab
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 

Was ist angesagt? (20)

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

Ähnlich wie Python Programming Essentials - M17 - Functions

CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Plataformatec
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxPragatheshP
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfBoomBoomers
 

Ähnlich wie Python Programming Essentials - M17 - Functions (20)

CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
C function
C functionC function
C function
 
4th unit full
4th unit full4th unit full
4th unit full
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Function in c
Function in cFunction in c
Function in c
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptx
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 

Mehr von P3 InfoTech Solutions Pvt. Ltd.

Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsP3 InfoTech Solutions Pvt. Ltd.
 

Mehr von P3 InfoTech Solutions Pvt. Ltd. (20)

Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web Development
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External Programs
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and Files
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdb
 
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging modulePython Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging module
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
 
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File OperationsPython Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File Operations
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and Packages
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python Programming Essentials - M15 - References
Python Programming Essentials - M15 - ReferencesPython Programming Essentials - M15 - References
Python Programming Essentials - M15 - References
 
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - DictionariesPython Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - Dictionaries
 
Python Programming Essentials - M13 - Tuples
Python Programming Essentials - M13 - TuplesPython Programming Essentials - M13 - Tuples
Python Programming Essentials - M13 - Tuples
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical Operators
 

Kürzlich hochgeladen

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Kürzlich hochgeladen (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Python Programming Essentials - M17 - Functions

  • 1. http://www.skillbrew.com /SkillbrewTalent brewed by the industry itself Functions in Python Pavan Verma @YinYangPavan 1 Founder, P3 InfoTech Solutions Pvt. Ltd. Python Programming Essentials
  • 2. © SkillBrew http://skillbrew.com What is a function A function is a block of organized, reusable code that is used to perform a single, related action 2
  • 3. © SkillBrew http://skillbrew.com Advantages of using functions 3 Reusability. Reducing duplication of code Decomposing complex problems into simpler pieces Abstraction Cleaner code
  • 4. © SkillBrew http://skillbrew.com Types of functions Types of Functions Built-in Functions User Defined Functions 4
  • 5. © SkillBrew http://skillbrew.com Defining a function 5 def functionName(): # do something def printList(): num_list = range(3) print num_list 1. def keyword is used to define a function 2. def keyword is followed by a function name 3. Function name is followed by parenthesis () 4. After this a block of python statements
  • 6. © SkillBrew http://skillbrew.com Calling a Function 6 def printList(): num_list = range(3) print num_list printList() Output: [0, 1, 2] To call a function, we specify the function name with the round brackets Call to function
  • 7. © SkillBrew http://skillbrew.com return keyword 7 def printList(): num_list = range(3) return num_list my_list = printList() print my_list Output: [0, 1, 2] 1. The return keyword is used to return values from a function 2. A function implicitly returns None by default even if you don’t use return keyword
  • 8. © SkillBrew http://skillbrew.com Parameterized functions 8 def printList(upper_limit): num_list = range(upper_limit) print "list: %s" % num_list printList(5) printList(2) Output: list: [0, 1, 2, 3, 4] list: [0, 1] 1. Names given in the function definition are called parameters 2. The values you supply in the function call are called arguments
  • 9. © SkillBrew http://skillbrew.com Default arguments 9 def printList(upper_limit=4): print "upper limit: %d" % upper_limit num_list = range(upper_limit) print "list: %s" % num_list printList(5) printList() Output: upper limit: 5 list: [0, 1, 2, 3, 4] upper limit: 4 list: [0, 1, 2, 3] value 4 1. When function is called without any arguments default value is used 2. During a function call if argument is passed then the passed value is used
  • 10. © SkillBrew http://skillbrew.com Default arguments (2) 10 A non-default argument may not follow default arguments while defining a function def printList(upper_limit=4, step):
  • 11. © SkillBrew http://skillbrew.com Keyword arguments 11 def printList(upper_limit, step=1): print "upper limit: %d" % upper_limit num_list = range(0, upper_limit, step) print "list: %s" % num_list printList(upper_limit=5, step=2) Output: upper limit: 5 list: [0, 2, 4] range() function has two variations: 1.range(stop) 2.range(start, stop[, step])
  • 12. © SkillBrew http://skillbrew.com Keyword arguments (2) 12 printList(step=2, upper_limit=5) printList(upper_limit=5, step=2) Advantages of using keyword arguments Using the function is easier since you don’t have to worry about or remember the order of the arguments
  • 13. © SkillBrew http://skillbrew.com Keyword arguments (3) 13 You can give values to only those parameters which you want, provided that the other parameters have default argument value printList(upper_limit=5)
  • 14. © SkillBrew http://skillbrew.com Keyword arguments (4) 14 A non-keyword argument cannot follow keyword arguments while calling a function printList(upper_limit=4, 10)
  • 15. © SkillBrew http://skillbrew.com global variables 15 counter = 10 def printVar(): print counter printVar() print "counter: %d" % counter Output: 10 counter: 10 Variable defined outside a function or class is a global variable counter is a global variable
  • 16. © SkillBrew http://skillbrew.com global variables (2) 16 counter = 10 def printVar(): counter = 20 print "Counter in: %d" % counter printVar() print "Counter out: %d" % counter Output: Counter in: 20 Counter out: 10 counter in function definition is local variable tied to function’s namespace Hence the value of global counter does not gets modified
  • 17. © SkillBrew http://skillbrew.com global variables (3) 17 counter = 10 def printVar(): global counter counter = 20 print "Counter in: %d" % counter printVar() print "Counter out: %d" % counter Output: Counter in: 20 Counter out: 20 In order to use the global counter variable inside the function you have to explicitly tell python to use global variable using global keyword
  • 18. © SkillBrew http://skillbrew.com docstrings 18 def add(x, y): """ Return the sum of inputs x, y """ return x + y print add.__doc__ Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods docstring Access a docstring using object.__doc__
  • 19. © SkillBrew http://skillbrew.com Summary  What is a function  Advantages of using functions  Defining a function  Calling a function  return keyword 19  Parameterized functions  Default arguments  Keyword arguments  global variables  docstrings
  • 20. © SkillBrew http://skillbrew.com Resources  Default arguments http://www.ibiblio.org/g2swap/byteofpython/read/default-argument- values.html  Keyword arguments http://www.ibiblio.org/g2swap/byteofpython/read/keyword- arguments.html  return keyword http://www.ibiblio.org/g2swap/byteofpython/read/return.html  local variables http://www.ibiblio.org/g2swap/byteofpython/read/local- variables.html  Docstrings http://www.ibiblio.org/g2swap/byteofpython/read/docstrings.html 20
  • 21. 21