You are on page 1of 8

Functions Unless otherwise noted, the content of this course material is licensed under a Creative

Chapter 4 Commons Attribution 3.0 License.


http://creativecommons.org/licenses/by/3.0/.

Copyright 2010, Charles Severance

Python for Informatics: Exploring Information


www.py4inf.com

Stored (and reused) Steps Python Functions


Program:
def
hello():
print “Hello”
def hello(): • There are two kinds of functions in Python.
print "Hello" Output:
print “Fun” print "Fun" • Built-in functions that are provided as part of Python - raw_input(),
Hello type(), float(), int() ...
hello() Fun
hello()
print “Zip” Zip • Functions that we define ourselves and then use
print “Zip” Hello
hello()
Fun • We treat the of the built-in function names as “reserved words” (i.e.
hello() we avoid them as variable names)

We call these reusable pieces of code “functions”.


Argument
Function Definition
big = max('Hello world')
Assignment
'w'
• In Python a function is some reusable code that takes arguments(s) as
input does some computation and then returns a result or results Result
>>> big = max('Hello world')
• We define a function using the def reserved word >>> print big
'w'
• We call/invoke the function by using the function name, parenthesis >>> tiny = min('Hello world')
and arguments in an expression >>> print tiny
''
>>>

Max Function Max Function


A function is some stored A function is some stored
>>> big = max('Hello world') >>> big = max('Hello world')
code that we use. A code that we use. A
>>> print big >>> print big
function takes some input function takes some input
'w' 'w'
and produces an output. and produces an output.

def max(inp):

“Hello world” max() ‘w’ “Hello world”


blah
blah ‘w’
(a string) function (a string) (a string) for x in y: (a string)
blah
blah

Guido wrote this code Guido wrote this code


String >>> sval = "123"
Type Conversions >>> print float(99) / 100 >>> type(sval)
0.99 Conversions <type 'str'>
>>> print sval + 1
>>> i = 42 Traceback (most recent call last):
>>> type(i) File "<stdin>", line 1, in <module>
<type 'int'> TypeError: cannot concatenate 'str' and 'int'
• When you put an integer and
>>> f = float(i) • You can also use int() and >>> ival = int(sval)
floating point in an expression float() to convert between >>> type(ival)
>>> print f
the integer is implicitly strings and integers <type 'int'>
42.0
converted to a float >>> print ival + 1
>>> type(f)
• You will get an error if the 124
• You can control this with the <type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
string does not contain >>> nsv = "hello bob"
>>> niv = int(nsv)
built in functions int() and float() numeric characters Traceback (most recent call last):
-2.5
File "<stdin>", line 1, in <module>
>>> ValueError: invalid literal for int()

Data Conversion Errors The try / except Structure

• Are you tired of seeing trace >>> ival = int(sval)


Traceback (most recent call last):
back errors?
File "<stdin>", line 1, in <module> • You surround a dangerous section of code with try and except.
• Do you want to do something ValueError: invalid literal for int()
about it? • If the code in the try works - the except is skipped

• Do you want to take control of error recovery? • If the code in the try fails - it jumps to the except section

• Then you should take advantage of the try/eccept capability in Python!


$ cat tryexcept.py
astr = "Hello Bob" When the first conversion fails - it
try: just drops into the except: clause and
istr = int(astr) the program continues.
$ cat notry.py except:
astr = "Hello Bob" $ python notry.py istr = -1
istr = int(astr) Traceback (most recent call last):
$ python tryexcept.py
The print "First", istr File "notry.py", line 6, in <module> print "First", istr
First -1
program istr = int(astr)
Second 123
stops astr = "123" ValueError: invalid literal for int() with astr = "123"
here istr = int(astr) base 10: 'Hello Bob' try:
print "Second", istr istr = int(astr) When the second conversion
All except: succeeds - it just skips the except:
Done istr = -1 clause and the program continues.

print "Second", istr

Math Library
(in radians)
(in radians)
(in radians)
(returns radians)
• Python also includes common
>>> import math
(returns radians)
math functions (returns radians)
>>> print math.sqrt(25.0)
• You must add import math to 5.0
your program to access this
library of functions
Trigonometry pi
----
Math Function Summary
Review 45
cos
4

• Radians represent the


• The math functions are there
length of an arc
when you need them
described by an angle in >>> import math
>>> import math
the unit circle (radius
1.0)
>>> print math.pi • Unless we are solving complex >>> print math.sqrt(25.0)
3.14159265359 trigonometry problems or 5.0
>>> print math.pi / 4 statistics problems - pretty
• So 45 degrees is pi / 4 or
0.785398163397 much all we use is the square
1/8 the way around the
>>> print math.cos(math.pi / 4) root
entire unit circle (2 * pi)
0.707106781187

Building our Own Functions x=5


print_lyrics():
print "I'm a lumberjack, and I'm okay."
print "I sleep all night and I work all day."

print “Hello”

• We create a new function using the def keyword followed by optional def print_lyrics():
parameters in parenthesis. print "I'm a lumberjack, and I'm okay."
print "I sleep all night and I work all day." Hello
• We indent the body of the function Yo
print “Yo” 7
• This defines the function but does not execute the body of the function
x=x+2
print x
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print "I sleep all night and I work all day."
Definitions and Uses 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."
• Once we have defined a function, we can call (or invoke) it as many
print “Yo”
times as we like
print_lyrics() Hello
• This is the store and reuse pattern x=x+2
print x
Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7

x=5
print “Hello”
Flow of Execution
Arguments
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
• An argument is a value we pass into the function as its input when we
call the function
print "I sleep all night and I work all day."
• We use arguments so we can direct the function to do different kinds
print “Yo” of work when we call it at different times
print_lyrics() Hello
x=x+2 Yo • We put the arguments in parenthesis after the name of the function
print x I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7 big = max('Hello world')
Argument
>>> def greet(lang): >>> def greet(lang):
Parameters ... if lang == 'es':
... return 'Hola' Return Value ... if lang == 'es':
... return 'Hola'
... elif lang == 'fr': ... elif lang == 'fr':
... return 'Bonjour' ... return 'Bonjour'
... else: ... else:
• A parameter is a variable ... return 'Hello' • A “fruitful” function is one ... return 'Hello'
which we use in the ... that produces a result (or ...
function definition that is a >>> print greet('en'),'Glenn' return value) >>> print greet('en'),'Glenn'
“handle” that allows the Hello Glenn Hello Glenn
code in the function to >>> print greet('es'),'Sally' • The return statement ends >>> print greet('es'),'Sally'
access the arguments for a Hola Sally the function execution and Hola Sally
particular function >>> print greet('fr'),'Michael' “sends back” the result of >>> print greet('fr'),'Michael'
invocation. Bonjour Michael the function Bonjour Michael
>>> >>>

Arguments, Parameters, and Results Multiple Parameters / Arguments


>>> big = max('Hello world')
Parameter
>>> print big
'w' • We can define more than def addtwo(a, b):
def max(inp): one parameter in the added = a + b
blah function definition return added
“Hello world” blah ‘w’
for x in y: • We simply add more
x = addtwo(3, 5)
arguments when we call the
Argument blah function print x
Result
blah
return ‘w’
Exercise
To function or not to function...
Rewrite your pay computation with time-and-a-half
for overtime and create a function called computepay
• Organize your code into “paragraphs” - capture a complete thought
which takes two parameters ( hours and rate).
and “name it”

• Don’t repeat yourself - make it work once and then reuse it Enter Hours: 45
Enter Rate: 10
• If something gets too long or complex, break up logical chunks and put Pay: 475.0
those chunks in functions

• Make a library of common stuff that you do over and over - perhaps 475 = 40 * 10 + 5 * 15
share this with your friends...

Note:Version 0.0.2 of the book has a typo on this problem

Summary
• Functions • Parameters
• Built-In Functions • Results (Fruitful functions)
• Type conversion (int, float) • Void (non-fruitful) functions
• Math functions (sin, sqrt) • Why use functions?
• Try / except (again)
• Arguments

You might also like