KEMBAR78
Python Details Functions Description.pptx
Functions
Chapter 4
Copyright 2010- Charles Severance
These slides are a derivative work based on the original slides, “Python for Informatics :
Exploring Information”, created by Charles Severance. The original slides are located at
www.pythonlearn.com
This modified set of slides was done by John Alexander (2013).
The primary purpose of this derivative work is to make the highest quality Python courseware
available to instructors so that they can teach Python, and insure that the slides are properly
formatted for easy, out-of-the-box, use by both Microsoft PowerPoint and OpenOffice Impress.
Unless otherwise noted, the content of this course material is licensed under a Creative
Commons Attribution 3.0 License (The “BY” variant of the license)
http://creativecommons.org/licenses/by/3.0/.
Creative Commons Attribution 3.0 License
Stored (and reused) Steps
Output:
Hello
Fun
Zip
Hello
Fun
Program:
def hello():
print
'Hello'
print 'Fun'
hello()
print 'Zip‘
hello()
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(), max(), min(), int(), str(), …
• Functions (user defined) that we define ourselves and then
use
• We treat the built-in function names like reserved words (i.e.
we avoid them as variable names)
Function 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 big
>>> w
>>> tiny = min('Hello
world')
>>> print tiny
>>>
big = max('Hello
world')
Argume
nt
Function
name
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.
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
the function name, optional parameters in parenthesis, and
then we add a colon.
• 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
Hell
o
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') Argume
nt
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 a 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’
‘w
’
Argume
nt
Paramet
er
Resu
lt
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
8
Void 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"
Functions – Code Reuse
• 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...
The range() function
• range() is a built-in
function that allows you
to create a sequence of
numbers in a range
• Very useful in “for” loops
which are discussed later
in the Iteration chapter
• Takes as an input 1, 2, or
3 arguments. See
examples.
x = range(5)
print x
[0, 1, 2, 3, 4]
x = range(3, 7)
print x
[3, 4, 5, 6]
x = range(10, 1, -2)
print x
[10, 8, 6, 4, 2]
Modules and the import
statement
• A program can load a
module file by using the
import statement
• Use the name of the
module
• Functions and variables
names in the module
must be qualified with
the module name. e.g.
math.pi
import math
radius = 2.0
area = math.pi * (radius ** 2)
12.5663706144
math.log(5)
1.6094379124341003
import sys
sys.exit()
Summary
• Functions
• Built-In Functions:
• int(), float(), str(), type(), min(), max(), dir(), range(), raw_input(),…
• Defining functions: the def keyword
• Arguments, Parameters, Results, and Return values
• Fruitful and Void functions
• The range() function

Python Details Functions Description.pptx

  • 1.
  • 2.
    Copyright 2010- CharlesSeverance These slides are a derivative work based on the original slides, “Python for Informatics : Exploring Information”, created by Charles Severance. The original slides are located at www.pythonlearn.com This modified set of slides was done by John Alexander (2013). The primary purpose of this derivative work is to make the highest quality Python courseware available to instructors so that they can teach Python, and insure that the slides are properly formatted for easy, out-of-the-box, use by both Microsoft PowerPoint and OpenOffice Impress. Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License (The “BY” variant of the license) http://creativecommons.org/licenses/by/3.0/. Creative Commons Attribution 3.0 License
  • 3.
    Stored (and reused)Steps Output: Hello Fun Zip Hello Fun Program: def hello(): print 'Hello' print 'Fun' hello() print 'Zip‘ hello() def print 'Hello' print 'Fun' hello() print “Zip” We call these reusable pieces of code “functions”. hello( ): hello()
  • 4.
    Python Functions • Thereare two kinds of functions in Python • Built-in functions that are provided as part of Python - raw_input(), type(), float(), max(), min(), int(), str(), … • Functions (user defined) that we define ourselves and then use • We treat the built-in function names like reserved words (i.e. we avoid them as variable names)
  • 5.
    Function Definition • InPython 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
  • 6.
    >>> big =max('Hello world') >>> print big >>> w >>> tiny = min('Hello world') >>> print tiny >>> big = max('Hello world') Argume nt Function name
  • 7.
    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.
  • 8.
    Type Conversions • When youput 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 canalso 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 OwnFunctions • We create a new function using the def keyword followed by the function name, optional parameters in parenthesis, and then we add a colon. • 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 Hell o 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 argumentis 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') Argume nt
  • 15.
    Parameters • A parameteris 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 • Oftena 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 a 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’ ‘w ’ Argume nt Paramet er Resu lt
  • 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 8
  • 20.
    Void Functions • Whena 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.
    Functions – CodeReuse • 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.
    The range() function •range() is a built-in function that allows you to create a sequence of numbers in a range • Very useful in “for” loops which are discussed later in the Iteration chapter • Takes as an input 1, 2, or 3 arguments. See examples. x = range(5) print x [0, 1, 2, 3, 4] x = range(3, 7) print x [3, 4, 5, 6] x = range(10, 1, -2) print x [10, 8, 6, 4, 2]
  • 23.
    Modules and theimport statement • A program can load a module file by using the import statement • Use the name of the module • Functions and variables names in the module must be qualified with the module name. e.g. math.pi import math radius = 2.0 area = math.pi * (radius ** 2) 12.5663706144 math.log(5) 1.6094379124341003 import sys sys.exit()
  • 24.
    Summary • Functions • Built-InFunctions: • int(), float(), str(), type(), min(), max(), dir(), range(), raw_input(),… • Defining functions: the def keyword • Arguments, Parameters, Results, and Return values • Fruitful and Void functions • The range() function