SlideShare a Scribd company logo
4
Most read
5
Most read
19
Most read
Function in Python
Stored (and reused) Steps
Output:
Hello
Fun
Zip
Hello
Fun
Program:
def thing():
print 'Hello’
print 'Fun’
thing()
print 'Zip’
thing()
def
print 'Hello'
print 'Fun'
hello()
print “Zip”
We call these reusable pieces of code “functions”.
hello():
hello()
Python Functions
• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python -
raw_input(), type(), float(), int() ...
• Functions that we define ourselves and then use
• We treat the of the built-in function names as "new" reserved
words (i.e. we avoid them as variable names)
Definition
• In Python a function is some reusable code that takes
arguments(s) as input does some computation and then returns
a result or results
• We define a function using the def reserved word
• We call/invoke the function by using the function name,
parenthesis and arguments in an expression
>>> big = max('Hello world')
>>> print bigw>>> tiny =
min('Hello world')
>>> print tiny>>>
big = max('Hello world')
Argument
'w'
Result
Assignment
Max Function
>>> big = max('Hello world')
>>> print big'w'
max()
function
“Hello world”
(a string)
‘w’
(a string)
A function is some
stored code that we
use. A function takes
some input and
produces an output.
Guido wrote this code
Max Function
>>> big = max('Hello world')
>>> print big'w'
def max(inp):
blah
blah
for x in y:
blah
blah
“Hello world”
(a string)
‘w’
(a string)
A function is some
stored code that we
use. A function takes
some input and
produces an output.
Guido wrote this code
Type Conversions
• When you put an integer and
floating point in an expression
the integer is implicitly
converted to a float
• You can control this with the
built in functions int() and
float()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
-2.5
>>>
String
Conversions
• You can also use int() and
float() to convert between
strings and integers
• You will get an error if the
string does not contain
numeric characters
>>> sval = '123'
>>> type(sval)
<type 'str'>
>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
>>> ival = int(sval)
>>> type(ival)
<type 'int'>
>>> print ival + 1
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Building our Own Functions
• We create a new function using the def keyword followed by
optional parameters in parenthesis.
• We indent the body of the function
• This defines the function but does not execute the body of the
function
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
print 'Yo'
x = x + 2
print x
Hello
Yo
7
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all
day.'
print_lyrics():
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it as
many times as we like
• This is the store and reuse pattern
x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
print 'Yo'
print_lyrics()
x = x + 2
print x
Hello
Yo
I'm a lumberjack, and I'm okay.I
sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input
when we call the function
• We use arguments so we can direct the function to do different
kinds of work when we call it at different times
• We put the arguments in parenthesis after the name of the
function
big = max('Hello world')
Argument
Parameters
• A parameter is a variable
which we use in the
function definition that is
a “handle” that allows the
code in the function to
access the arguments for
a particular function
invocation.
>>> def greet(lang):
... if lang == 'es':
... print 'Hola’
... elif lang == 'fr':
... print 'Bonjour’
... else:
... print 'Hello’
...
>>> greet('en')Hello
>>> greet('es')Hola
>>> greet('fr')Bonjour
>>>
Return Values
• Often a function will take its arguments, do some computation
and return a value to be used as the value of the function call in
the calling expression. The return keyword is used for this.
def greet():
return "Hello”
print greet(), "Glenn”
print greet(), "Sally"
Hello Glenn
Hello Sally
Return Value
• A “fruitful” function is one
that produces a result (or
return value)
• The return statement
ends the function
execution and “sends
back” the result of the
function
>>> def greet(lang):
... if lang == 'es':
... return 'Hola’
... elif lang == 'fr':
... return 'Bonjour’
... else:
... return 'Hello’
... >>> print greet('en'),'Glenn’
Hello Glenn
>>> print greet('es'),'Sally’
Hola Sally
>>> print greet('fr'),'Michael’
Bonjour Michael
>>>
Arguments, Parameters, and
Results
>>> big = max('Hello world')
>>> print big'w'
def max(inp):
blah
blah
for x in y:
blah
blah
return ‘w’
“Hello world” ‘w’
Argument
Parameter
Result
Multiple Parameters /
Arguments
• We can define more than
one parameter in the
function definition
• We simply add more
arguments when we call
the function
• We match the number and
order of arguments and
parameters
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print x
Void (non-fruitful) Functions
• When a function does not return a value, we call it a "void"
function
• Functions that return values are "fruitful" functions
• Void functions are "not fruitful"
To function or not to function...
• Organize your code into “paragraphs” - capture a complete
thought and “name it”
• Don’t repeat yourself - make it work once and then reuse it
• If something gets too long or complex, break up logical chunks
and put those chunks in functions
• Make a library of common stuff that you do over and over -
perhaps share this with your friends...
Exercise
Rewrite your pay computation with time-and-a-
half for overtime and create a function called
computepay which takes two parameters ( hours
and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Summary
• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Try / except (again)
• Arguments
• Parameters

More Related Content

What's hot (20)

PDF
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
PPTX
Templates in C++
Tech_MX
 
PPT
Repetition Structure
PRN USM
 
PDF
Numpy tutorial
HarikaReddy115
 
PDF
Date and Time Module in Python | Edureka
Edureka!
 
PDF
Set methods in python
deepalishinkar1
 
PPTX
Python Exception Handling
Megha V
 
PPTX
Basic data types in python
sunilchute1
 
PDF
Python recursion
Prof. Dr. K. Adisesha
 
PPTX
Constructor and Types of Constructors
Dhrumil Panchal
 
PDF
Tuples in Python
DPS Ranipur Haridwar UK
 
PPTX
Class, object and inheritance in python
Santosh Verma
 
PPTX
Python list
ArchanaBhumkar
 
PDF
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Edureka!
 
PDF
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
Operators in python
deepalishinkar1
 
PPTX
Map, Filter and Reduce In Python
Simplilearn
 
PPSX
Modules and packages in python
TMARAGATHAM
 
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Templates in C++
Tech_MX
 
Repetition Structure
PRN USM
 
Numpy tutorial
HarikaReddy115
 
Date and Time Module in Python | Edureka
Edureka!
 
Set methods in python
deepalishinkar1
 
Python Exception Handling
Megha V
 
Basic data types in python
sunilchute1
 
Python recursion
Prof. Dr. K. Adisesha
 
Constructor and Types of Constructors
Dhrumil Panchal
 
Tuples in Python
DPS Ranipur Haridwar UK
 
Class, object and inheritance in python
Santosh Verma
 
Python list
ArchanaBhumkar
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Edureka!
 
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
Python: Modules and Packages
Damian T. Gordon
 
Operators in python
deepalishinkar1
 
Map, Filter and Reduce In Python
Simplilearn
 
Modules and packages in python
TMARAGATHAM
 

Similar to Function in Python [Autosaved].ppt (20)

PPTX
Pythonlearn-04-Functions (1).pptx
leavatin
 
PPTX
Python Learn Function with example programs
GeethaPanneer
 
PPTX
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
PDF
Chapter Functions for grade 12 computer Science
KrithikaTM
 
PDF
Notes5
hccit
 
PPT
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
PPTX
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
PDF
Python Function.pdf
NehaSpillai1
 
PPTX
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
PPTX
Python Lecture 4
Inzamam Baig
 
PDF
functions- best.pdf
MikialeTesfamariam
 
PPTX
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
PPT
functions _
SwatiHans10
 
PPTX
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
PPTX
function in python programming languges .pptx
rundalomary12
 
PDF
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
PPTX
Functions_new.pptx
Yagna15
 
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
PDF
Functions2.pdf
prasnt1
 
PPTX
UNIT 3 python.pptx
TKSanthoshRao
 
Pythonlearn-04-Functions (1).pptx
leavatin
 
Python Learn Function with example programs
GeethaPanneer
 
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Notes5
hccit
 
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Python Function.pdf
NehaSpillai1
 
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
Python Lecture 4
Inzamam Baig
 
functions- best.pdf
MikialeTesfamariam
 
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
functions _
SwatiHans10
 
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
function in python programming languges .pptx
rundalomary12
 
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
Functions_new.pptx
Yagna15
 
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Functions2.pdf
prasnt1
 
UNIT 3 python.pptx
TKSanthoshRao
 
Ad

Recently uploaded (20)

PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Ad

Function in Python [Autosaved].ppt

  • 2. Stored (and reused) Steps Output: Hello Fun Zip Hello Fun Program: def thing(): print 'Hello’ print 'Fun’ thing() print 'Zip’ thing() def print 'Hello' print 'Fun' hello() print “Zip” We call these reusable pieces of code “functions”. hello(): hello()
  • 3. Python Functions • There are two kinds of functions in Python. • Built-in functions that are provided as part of Python - raw_input(), type(), float(), int() ... • Functions that we define ourselves and then use • We treat the of the built-in function names as "new" reserved words (i.e. we avoid them as variable names)
  • 4. Definition • In Python a function is some reusable code that takes arguments(s) as input does some computation and then returns a result or results • We define a function using the def reserved word • We call/invoke the function by using the function name, parenthesis and arguments in an expression
  • 5. >>> big = max('Hello world') >>> print bigw>>> tiny = min('Hello world') >>> print tiny>>> big = max('Hello world') Argument 'w' Result Assignment
  • 6. Max Function >>> big = max('Hello world') >>> print big'w' max() function “Hello world” (a string) ‘w’ (a string) A function is some stored code that we use. A function takes some input and produces an output. Guido wrote this code
  • 7. Max Function >>> big = max('Hello world') >>> print big'w' def max(inp): blah blah for x in y: blah blah “Hello world” (a string) ‘w’ (a string) A function is some stored code that we use. A function takes some input and produces an output. Guido wrote this code
  • 8. Type Conversions • When you put an integer and floating point in an expression the integer is implicitly converted to a float • You can control this with the built in functions int() and float() >>> print float(99) / 100 0.99 >>> i = 42 >>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print 1 + 2 * float(3) / 4 - 5 -2.5 >>>
  • 9. String Conversions • You can also use int() and float() to convert between strings and integers • You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) <type 'str'> >>> print sval + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) <type 'int'> >>> print ival + 1 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int()
  • 10. Building our Own Functions • We create a new function using the def keyword followed by optional parameters in parenthesis. • We indent the body of the function • This defines the function but does not execute the body of the function def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.'
  • 11. x = 5 print 'Hello' def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.' print 'Yo' x = x + 2 print x Hello Yo 7 print "I'm a lumberjack, and I'm okay." print 'I sleep all night and I work all day.' print_lyrics():
  • 12. Definitions and Uses • Once we have defined a function, we can call (or invoke) it as many times as we like • This is the store and reuse pattern
  • 13. x = 5 print 'Hello' def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.' print 'Yo' print_lyrics() x = x + 2 print x Hello Yo I'm a lumberjack, and I'm okay.I sleep all night and I work all day. 7
  • 14. Arguments • An argument is a value we pass into the function as its input when we call the function • We use arguments so we can direct the function to do different kinds of work when we call it at different times • We put the arguments in parenthesis after the name of the function big = max('Hello world') Argument
  • 15. Parameters • A parameter is a variable which we use in the function definition that is a “handle” that allows the code in the function to access the arguments for a particular function invocation. >>> def greet(lang): ... if lang == 'es': ... print 'Hola’ ... elif lang == 'fr': ... print 'Bonjour’ ... else: ... print 'Hello’ ... >>> greet('en')Hello >>> greet('es')Hola >>> greet('fr')Bonjour >>>
  • 16. Return Values • Often a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this. def greet(): return "Hello” print greet(), "Glenn” print greet(), "Sally" Hello Glenn Hello Sally
  • 17. Return Value • A “fruitful” function is one that produces a result (or return value) • The return statement ends the function execution and “sends back” the result of the function >>> def greet(lang): ... if lang == 'es': ... return 'Hola’ ... elif lang == 'fr': ... return 'Bonjour’ ... else: ... return 'Hello’ ... >>> print greet('en'),'Glenn’ Hello Glenn >>> print greet('es'),'Sally’ Hola Sally >>> print greet('fr'),'Michael’ Bonjour Michael >>>
  • 18. Arguments, Parameters, and Results >>> big = max('Hello world') >>> print big'w' def max(inp): blah blah for x in y: blah blah return ‘w’ “Hello world” ‘w’ Argument Parameter Result
  • 19. Multiple Parameters / Arguments • We can define more than one parameter in the function definition • We simply add more arguments when we call the function • We match the number and order of arguments and parameters def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print x
  • 20. Void (non-fruitful) Functions • When a function does not return a value, we call it a "void" function • Functions that return values are "fruitful" functions • Void functions are "not fruitful"
  • 21. To function or not to function... • Organize your code into “paragraphs” - capture a complete thought and “name it” • Don’t repeat yourself - make it work once and then reuse it • If something gets too long or complex, break up logical chunks and put those chunks in functions • Make a library of common stuff that you do over and over - perhaps share this with your friends...
  • 22. Exercise Rewrite your pay computation with time-and-a- half for overtime and create a function called computepay which takes two parameters ( hours and rate). Enter Hours: 45 Enter Rate: 10 Pay: 475.0 475 = 40 * 10 + 5 * 15
  • 23. Summary • Functions • Built-In Functions • Type conversion (int, float) • Math functions (sin, sqrt) • Try / except (again) • Arguments • Parameters