0% found this document useful (0 votes)
17 views

Py4Inf 04 Functions

The document discusses Python functions including defining functions, calling functions, arguments, parameters, return values, and type conversions. Functions are reusable blocks of code that take inputs and produce outputs. Functions are defined using the def keyword and called by their name. Arguments are values passed into a function and parameters refer to the variables in the function definition.

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Py4Inf 04 Functions

The document discusses Python functions including defining functions, calling functions, arguments, parameters, return values, and type conversions. Functions are reusable blocks of code that take inputs and produce outputs. Functions are defined using the def keyword and called by their name. Arguments are values passed into a function and parameters refer to the variables in the function definition.

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Functions

Chapter 4

Python for Informatics: Exploring Information


www.py4inf.com
Unless otherwise noted, the content of this course material is licensed under a Creative
Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/.

Copyright 2010,2011 Charles R. Severance


Stored (and reused) Steps
Program:
def
hello():
def hello():
print 'Hello' print 'Hello' Output:
print 'Fun' print 'Fun'
Hello
hello() Fun
hello()
print 'Zip' Zip
print “Zip” hello() Hello
Fun
hello()
We call these reusable pieces of code “functions”.
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)
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
Argument

big = max('Hello world')


Assignment
'w'
Result
>>> big = max('Hello world')
>>> print big
w
>>> tiny = min('Hello world')
>>> print tiny

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

“Hello world” max() ‘w’


(a string) function (a string)

Guido wrote this code


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

def max(inp):
blah
“Hello world” blah ‘w’
(a string) for x in y: (a string)
blah
blah

Guido wrote this code


Type Conversions >>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
• When you put an integer and
>>> f = float(i)
floating point in an expression
>>> print f
the integer is implicitly
42.0
converted to a float
>>> type(f)
• You can control this with the <type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
built in functions int() and float()
-2.5
>>>
String >>> sval = '123'
>>> type(sval)
Conversions <type 'str'>
>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
• You can also use int() and >>> ival = int(sval)
float() to convert between >>> type(ival)
strings and integers <type 'int'>
>>> print ival + 1
• You will get an error if the 124
>>> nsv = 'hello bob'
string does not contain
>>> niv = int(nsv)
numeric characters 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.'
print "I'm a lumberjack, and I'm okay."
print_lyrics(): 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.' Hello
Yo
print 'Yo' 7
x=x+2
print x
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() Hello
x=x+2 Yo
print x 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
>>> def greet(lang):
Parameters ...
...
if lang == 'es':
print 'Hola'
... elif lang == 'fr':
... print 'Bonjour'
... else:
• A parameter is a variable ... print 'Hello'
which we use in the ...
function definition that is a >>> greet('en')
“handle” that allows the Hello
code in the function to >>> greet('es')
access the arguments for a Hola
particular function >>> greet('fr')
invocation. Bonjour
>>>
>>> def greet(lang):
Return Value ...
...
if lang == 'es':
return 'Hola'
... elif lang == 'fr':
... return 'Bonjour'
... else:
• A “fruitful” function is one ... return 'Hello'
that produces a result (or ...
return value) >>> print greet('en'),'Glenn'
Hello Glenn
• The return statement ends >>> print greet('es'),'Sally'
the function execution and Hola Sally
“sends back” the result of >>> print greet('fr'),'Michael'
the function Bonjour Michael
>>>
Arguments, Parameters, and Results
>>> big = max('Hello world')
Parameter
>>> print big
'w'
def max(inp):
blah
“Hello world” blah ‘w’
for x in y:
Argument blah
Result
blah
return ‘w’
Multiple Parameters / Arguments
• We can define more than
one parameter in the
function definition def addtwo(a, b):
added = a + b
• We simply add more
return added
arguments when we call the
function
x = addtwo(3, 5)
print x
• We match the number and
order of arguments and
parameters
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...
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
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

You might also like