cse 231, rich enbodycse231/lectures/enbody/day09/09... · f = celsius2fahrenheit(c) print(f) def...
TRANSCRIPT
1
Functions
CSE 231, Rich Enbody
Michigan State University CSE 231, Fall 2013
Intro to Functions 2
From Mathematics we know that functions perform some operation
and return one value.
2
Michigan State University CSE 231, Fall 2013
Intro to Functions 3
Functions “encapsulate” the performance of some operation,
so it can be used by others. (for example, the sqrt() function)
Michigan State University CSE 231, Fall 2013
Intro to Functions 4
Consider a function to convert Celsius to Fahrenheit: Formula: F = C * 1.8 + 32.0 Functional notation:
F = g(C) where g(C) = C*1.8 + 32.0
3
Michigan State University CSE 231, Fall 2013
Intro to Functions 5
Invocation Math: F= g(C) Python: F = g(C)
Terminology: argument “C”
Michigan State University CSE 231, Fall 2013
Intro to Functions 6
Definition Math: g(C) = C*1.8 + 32.0 Python:
def g(C): return C*1.8 + 32.0
Terminology: parameter “C”
4
Michigan State University CSE 231, Fall 2013
Intro to Functions 7
Terminology § Invocation (Call)
F = g(C) § Definition
def g(C): return C*1.8 + 32.0
keyword indicating function being defined indented
function body (suite)
function name; must meet regular variable naming rules
: indicates the body of the function follows
in parenthesis is a list of parameters being passed
Michigan State University CSE 231, Fall 2013
Intro to Functions 8
Python function call (invocation): F = g(0.0)
function name; must have previously been defined
in parenthesis is a list of arguments (expressions)
5
Michigan State University CSE 231, Fall 2013
Intro to Functions 9
def g(Temp): return Temp*1.8 + 32.0
F = g(C)
1. Call copies argument C to parameter Temp
2. Control transfers to function “g”
Michigan State University CSE 231, Fall 2013
Intro to Functions 10
3. Expression in g is evaluated
4. Value of expression is returned to the invoker
F = g(C)
def g(Temp): return Temp*1.8 + 32.0
6
Michigan State University CSE 231, Fall 2013
Intro to Functions 11
Operation
Defines celsius2Fahrenheit (associates the function body to the name celsius2Fahrenheit) f = celsius2Fahrenheit(c)
print(f)
def celsius2Fahrenheit (x): return x*1.8 + 32.0 c = 100
celsius2Fahrenheit name space
Michigan State University CSE 231, Fall 2013
Intro to Functions 12
Operation
Associates the value 100 to the variable c.
f = celsius2Fahrenheit(c) print(f)
def celsius2Fahrenheit (x): return x*1.8 + 32.0 c = 100
celsius2Fahrenheit
name space
100 c
7
Michigan State University CSE 231, Fall 2013
Intro to Functions 13
f = celsius2Fahrenheit(c) print(f)
def celsius2Fahrenheit (x): return x*1.8 + 32.0 c = 100
Operation
Invocation: Creates a local namespace for celsius2Fahrenheit.
Associates the value of the parameter x to argument c (associates 100 with x).
x c2f name space
celsius2Fahrenheit c
name space
100
Michigan State University CSE 231, Fall 2013
Intro to Functions 14
Operation
Transfers control to function celsius2Farenheit
f = celsius2Fahrenheit(c) print(f)
def celsius2Fahrenheit (x): return x*1.8 + 32.0 c = 100
c2f name space
celsius2Fahrenheit c
name space
100
x
8
Michigan State University CSE 231, Fall 2013
Intro to Functions 15
Operation
Return command: evaluates the expression
f = celsius2Fahrenheit(c) print(f)
def celsius2Fahrenheit (x): return x*1.8 + 32.0 c = 100
c2f name space
celsius2Fahrenheit c
name space
100
x
Michigan State University CSE 231, Fall 2013
Intro to Functions 16
f = celsius2Fahrenheit(c) print(f)
def celsius2Fahrenheit (x): return x*1.8 + 32.0 c = 100
Operation
Returns the value: 212.
(212) Return command:
Evaluates the expression.
Parameter x exists only in the function celsius2Fahrenheit’s namespace
c2f name space
celsius2Fahrenheit c
name space
100
x
212
Function namespace deleted.
f
f added to namespace and associated with 212.
9
Michigan State University CSE 231, Fall 2013
Intro to Functions 17
Operation
Continues sequential execution
celsius2… = … Name space
c = 100
f = celsius2Fahrenheit(c) print f . . .
def celsius2Fahrenheit (x): return x*1.8 + 32.0; . . . c = 100 . . .
f = 212
Michigan State University CSE 231, Fall 2013
Intro to Functions 18
Verbose Python Invocation
Math: F= g(C) Python: cels_temp = 100 fahr_temp = celsius_to_fahrenheit(cels_temp) print(cels_temp,’in Fahrenheit is:‘,fahr_temp)
10
Example 16 simpleFns
This example illustrates the construction and use of several functions.
Michigan State University CSE 231, Fall 2013
Intro to Functions 20
Verbose Python Definition
Math: g(C) = C*1.8 + 32.0 Python: def celsius_to_fahrenheit(cels_temp): return cels_temp*1.8 + 32.0
11
Michigan State University CSE 231, Fall 2013
Intro to Functions 21
Program Abstraction
1. Get Temperature 2. Convert Temperature 3. Display Temperature
Michigan State University CSE 231, Fall 2013
Intro to Functions 22
Needed Behavior
Please enter a temperature in degrees Celsius: 19.5 Original: 19.5 C Equivalent: 67.1 F
12
Michigan State University CSE 231, Fall 2013
Intro to Functions 23
def get_temp(): cels_temp = input(\
“Please enter \
temperature in degrees \
Celsius: ")
return float(cels_temp)
Get a temperature
Michigan State University CSE 231, Fall 2013
Intro to Functions 24
Convert
def celsius_to_fahrenheit(cels_temp): result = cels_temp*1.8+32.0
return result
13
Michigan State University CSE 231, Fall 2013
Intro to Functions 25
Display results
def display(cels_temp,fahr_temp): print("Original: ",cels_temp)
print("Equivalent:",fahr_temp)
print()
Michigan State University CSE 231, Fall 2013
Intro to Functions 26
The function arguments are passed in order
to the function parameters. The names need not match.
14
Michigan State University CSE 231, Fall 2013
Intro to Functions 27
When a function runs, it defines a new namespace.
The names in the function’s namespace are only available to the function.
Michigan State University CSE 231, Fall 2013
Intro to Functions 28
Passing arguments by reference: the first argument
passes its namespace reference to the first parameter,
second to second, and so on.
What gets passed?
15
Michigan State University CSE 231, Fall 2013
Intro to Functions 29
my_int = 25 my_function(my_int) print(my_int)
def my_function(an_int): print(an_int)
main namespace
my_int 25 reference
my_function namespace
an_int reference
Python objects
Michigan State University CSE 231, Fall 2013
Intro to Functions 30
Both namespaces now refer to the same object: the reference got passed.
What happens
if the function changes that variable?
16
Michigan State University CSE 231, Fall 2013
Intro to Functions 31
my_int = 25 my_function(my_int) print(my_int)
def my_function(an_int): an_int = 37 print(an_int)
main namespace
my_int 25 reference
my_function namespace
an_int
reference
Python objects
37
Michigan State University CSE 231, Fall 2013
Intro to Functions 32
The object (int) is immutable: it wasn’t changed.
The function namespace simply updated its reference to a new object. The reference in the calling program
was unaffected.
17
Michigan State University CSE 231, Fall 2013
Intro to Functions 33
my_list = [1,2,3] my_function(my_list) print(my_list)
def my_function(a_list): a_list[0] = 100 print(a_list)
main namespace
my_list [1,2,3] reference
my_function namespace
a_list
reference
Python objects
100
Michigan State University CSE 231, Fall 2013
Intro to Functions 34
Local Objects
A function has its own namespace (“local”), so § a parameter is in the function’s namespace so
any use outside the function is an error. § any variable assigned in the function is in the
function’s namespace so it is not available outside of the function.
18
Michigan State University CSE 231, Fall 2013
Intro to Functions 35
a = 25 my_function(a) print(a)
def my_function(b): a = 37 print(a, b)
main namespace
a 25
reference
my_function namespace
b
reference
Python objects
37
a
Why Functions?
19
Michigan State University CSE 231, Fall 2013
Intro to Functions 37
Functions for better design § Functions are very useful to break the
program down into small, understandable, maintainable pieces
§ Example: § def get_temp(None)
§ def celsius_to_fahrenheit(temp)
§ def display(fahr_temp, cels_temp)
Michigan State University CSE 231, Fall 2013
Intro to Functions 38
Software engineering
§ There is a discipline of computer science dedicated to the systematic development and maintenance of software.
§ There are a number of approaches that SE use: modularization, proveability, testing, refactoring and others.
20
Michigan State University CSE 231, Fall 2013
Intro to Functions 39
Refactoring: reexamine code to improve its readability
while not changing its functionality.
For example, extracting complicated code into multiple functions,
creating better abstractions.
Michigan State University CSE 231, Fall 2013
Intro to Functions 40
Function “rules of thumb”
§ Should do one thing. A function abstracts one idea.
§ Should not be overly long (~one page of code).
§ Best if generic so it could be reused elsewhere.
21
Michigan State University CSE 231, Fall 2013
Intro to Functions 41
Functions
§ Reuse § Abstraction (Encapsulation)
PerfectNumbers Fn
22
Michigan State University CSE 231, Fall 2013
Intro to Functions 43
List passed but not returned
§ In classify_value, a list is passed but never returned
§ This is because the calling program and the function share the same reference, and since the list is mutable a change in the function is a change to the calling program.
Michigan State University CSE 231, Fall 2013
Intro to Functions 44
Our own data structure
§ The variable result defines our own data structure: o the first element is a list o the second and third are integers
§ We add perfect numbers to the first list, and keep the abundant and deficient in the two counts
23
Michigan State University CSE 231, Fall 2013
Intro to Functions 45
isolate complicated printing
§ print_results isolates the messy formatting of the output
§ hiding complicated details is one thing that functions do well.
mileage puzzle
24
Michigan State University CSE 231, Fall 2013
Intro to Functions 47
Car Talk Puzzler
The Palindromic Odometer Driving along, Terry notices that the last four digits on the odometer are palindromic. A mile later, the last five digits are palindromic. A mile later, the middle four digits are palindromic. One mile after that, all six are palindromic. What was the odometer reading when Terry first looked at it?
Michigan State University CSE 231, Fall 2013
Intro to Functions 48
making a main function
§ it is common to create the main function that starts the whole program running
§ now when we run our file, it defines the main function which we must call manually.
25
Michigan State University CSE 231, Fall 2013
Intro to Functions 49
extensive use of continue
§ checks for ‘non-palindromes’ under the required circumstances and continues
§ makes the process more efficient.
Michigan State University CSE 231, Fall 2013
Intro to Functions 50
checking time
import time start = time.time()
#... do stuff ...
end = time.time()
print(‘It took:’,end-start,’seconds’)
26
Michigan State University CSE 231, Fall 2013
Intro to Functions 51
refactoring
§ what if you want to check a different approach to palindrome?
§ It is easy to refactor this program. Provide a new function with a different definition to see the effect.
§ functions make refactoring easier