06 Functions

68
Functions Chapter 4 Python for Informatics: Exploring Information www.pythonlearn.com

description

python fuctions

Transcript of 06 Functions

FunctionsChapter 4

Python for Informatics: Exploring Information

www.pythonlearn.com

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

TopicsIntroduction to FunctionsDefining and Calling a Void FunctionDesigning a Program to Use FunctionsLocal VariablesPassing Arguments to FunctionsGlobal Variables and Global Constants

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Topics (cont’d.)Introduction to Value-Returning Functions: Generating Random NumbersWriting Your Own Value-Returning FunctionsThe math ModuleStoring Functions in Modules

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Introduction to FunctionsFunction: group of statements within a program that perform as specific task

Usually one task of a large programFunctions can be executed in order to perform overall program task

Known as divide and conquer approachModularized program: program wherein each task within the program is in its own function

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Benefits of Modularizing a Program with Functions

The benefits of using functions include:Simpler codeCode reuse

write the code once and call it multiple times Better testing and debugging

Can test and debug each function individuallyFaster developmentEasier facilitation of teamwork

Different team members can write different functions

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Void Functions and Value-Returning Functions

A void function:Simply executes the statements it contains and then terminates.

A value-returning function:Executes the statements it contains, and then it returns a value back to the statement that called it.

The input, int, and float functions are examples of value-returning functions.

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Defining and Calling a FunctionFunctions are given names

Function naming rules:Cannot use key words as a function nameCannot contain spacesFirst character must be a letter or underscoreAll other characters must be a letter, number or underscoreUppercase and lowercase characters are distinct

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Defining and Calling a Function (cont’d.)Function name should be descriptive of the task carried out by the function

Often includes a verbFunction definition: specifies what function does def function_name():

statementstatement

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Defining and Calling a Function (cont’d.)Function header: first line of function– Includes keyword def and function name, followed by

parentheses and colonBlock: set of statements that belong together as a group– Example: the statements included in a function

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Defining and Calling a Function (cont’d.)Call a function to execute it

When a function is called:Interpreter jumps to the function and executes statements in the blockInterpreter jumps back to part of program that called the function

Known as function return

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Defining and Calling a Function (cont’d.)main function: called when the program starts

Calls other functions when they are needed Defines the mainline logic of the program

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Indentation in PythonEach block must be indented

Lines in block must begin with the same number of spacesUse tabs or spaces to indent lines in a block, but not both as this can confuse the Python interpreterIDLE automatically indents the lines in a block

Blank lines that appear in a block are ignored

Stored (and reused) Steps

Output:

HelloFunZipHelloFun

Program:

def thing(): print 'Hello' print 'Fun' thing()print 'Zip'thing()

def print 'Hello'print 'Fun'

thing()

We call these reusable pieces of code “functions”

thing():

thing()

print 'Zip'

Python Functions• There are two kinds of functions in Python.

>Built-in functions that are provided as part of Python - input(), type(), float(), int() ...

>Functions that we define ourselves and then use• We treat 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, parentheses, 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 bigw

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

def max(inp): blah blah for x in y: blah blah

'Hello world' (a string)

'w'(a string)

Guido wrote this code

>>> big = max('Hello world')>>> print bigw

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) / 1000.99>>> i = 42>>> type(i)<type 'int'>>>> f = float(i)>>> print f42.0>>> type(f)<type 'float'>>>> print 1 + 2 * float(3) / 4 - 5-2.5>>>

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 22

Built-in Functions and math Module >>> max(2, 3, 4) # Returns a maximum number4>>> min(2, 3, 4) # Returns a minimu number2>>> round(3.51) # Rounds to its nearest integer4>>> round(3.4) # Rounds to its nearest integer3>>> abs(-3) # Returns the absolute value3>>> pow(2, 3) # Same as 2 ** 38

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 23

The math Functions Function Description Example

fabs(x) Returns the absolute value of the argument. fabs(-2) is 2

ceil(x) Rounds x up to its nearest integer and ceil(2.1) is 3

returns this integer. ceil(-2.1) is -2

floor(x) Rounds x down to its nearest integer and floor(2.1) is 2

returns this integer. floor(-2.1) is -3

exp(x) Returns the exponential function of x (e^x). exp(1) is 2.71828

log(x) Returns the natural logarithm of x. log(2.71828) is 1.0

log(x, base) Returns the logarithm of x for the specified log10(10, 10) is 1

base.

sqrt(x) Returns the square root of x. sqrt(4.0) is 2

sin(x) Returns the sine of x. x represents an angle sin(3.14159 / 2) is 1

in radians. sin(3.14159) is 0

asin(x) Returns the angle in radians for the inverse asin(1.0) is 1.57

of sine. asin(0.5) is 0.523599

cos(x) Returns the cosine of x. x represents an cos(3.14159 / 2) is 0

angle in radians. cos(3.14159) is -1

acos(x) Returns the angle in radians for the inverse acos(1.0) is 0

of cosine. acos(0.5) is 1.0472

tan(x) Returns the tangent of x. x represents an tan(3.14159 / 4) is 1

angle in radians. tan(0.0) is 0

fmod(x, y) Returns the remainder of x/y as double. fmod(2.4, 1.3) is 1.1

degrees(x) Converts angle x from radians to degrees degrees(1.57) is 90

radians(x) Converts angle x from degrees to radians radians(90) is 1.57

MathFunctions

Run

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 + 1Traceback (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 + 1124>>> 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 parentheses• 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 = 5print '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 + 2print x

HelloYo7

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

Anyone with a birthday Today?

x = 5print '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 + 2print x

HelloYoI'm a lumberjack, and I'm okay.I sleep all night and I work all day.7

def happyBirthdayEmily():'''Function that says happy birthday to Emily.'''

print("Happy Birthday to you!")print("Happy Birthday to you!")print("Happy Birthday, dear Emily.")print("Happy Birthday to you!")

'''Function with parameter.'''

def happyBirthday(person): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear “, person, ".") print("Happy Birthday to you!")

happyBirthday('Emily')happyBirthday('Andre')

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 parentheses after the name of

the functionbig = max('Hello world')

Argument

ParametersA parameter is a variable which we use in the function definition. It 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 ValuesOften 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 GlennHello 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 bigw

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

8

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”

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 38

Defining FunctionsA function is a collection of statements that are grouped together to perform an operation.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 39

Function HeaderA function contains a header and body. The header begins with the def keyword, followed by function’s name and parameters, followed by a colon.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 40

Formal ParametersThe variables defined in the function header are known as formal parameters.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 41

Actual ParametersWhen a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 42

Return ValueA function may return a value using the return keyword.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 43

Scope of VariablesScope: the part of the program where the

variable can be referenced.

A variable created inside a function is referred to as a local variable. Local variables can only be accessed inside a function. The scope of a local variable starts from its creation and continues to the end of the function that contains the variable.

In Python, you can also use global variables. They are created outside all functions and are accessible to all functions in their scope.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Local Variables

Local variable: variable that is assigned a value inside a function– Belongs to the function in which it was created

Only statements inside that function can access it, error will occur if another function tries to access the variable

Scope: the part of a program in which a variable may be accessed– For local variable: function in which created

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Local Variables (cont’d.)

Local variable cannot be accessed by statements inside its function which precede its creation

Different functions may have local variables with the same name

Each function does not see the other function’s local variables, so no confusion

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 46

Defining FunctionsA function is a collection of statements that are grouped together to perform an operation.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 47

Function HeaderA function contains a header and body. The header begins with the def keyword, followed by function’s name and parameters, followed by a colon.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 48

Formal ParametersThe variables defined in the function header are known as formal parameters.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 49

Actual ParametersWhen a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 50

Return ValueA function may return a value using the return keyword.

def max(num1, num2):

if num1 > num2: result = num1 else: result = num2 return result

function name formal parameters

return value

function body

function header

Define a function Invoke a function

z = max(x, y)

actual parameters (arguments)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 51

Calling FunctionsTesting the max function

This program demonstrates calling a function max to return the largest of the int values

TestMax Run

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 52

Calling Functions, cont.animation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 53

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

Invoke the main function

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 54

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

i is now 5

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 55

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

j is now 2

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 56

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

invoke max(i, j)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 57

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

invoke max(i, j)Pass the value of i to num1Pass the value of j to num2

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 58

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

(num1 > num2) is true since num1 is 5 and num2 is 2

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 59

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

result is now 5

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 60

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

return result, which is 5

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 61

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

return max(i, j) and assign the return value to k

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 62

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

Execute the print statement

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 63

Trace Function Invocationanimation

def main(): i = 5 j = 2 k = max(i, j) print("The maximum between", i, "and", j, "is", k)

def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result

pass int 5

pass int 2

main()

Return to the caller

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 64

Call Stacks

(a) The main function is invoked.

Space required for the main function

j: 2 i: 5

(b) The max function is invoked.

(c) The max function is being executed.

Space required for the main function

j: i:

Space required for the max function

num2: num1:

int object 5

int object 2

This is a heap for storing objects

stack stack

int object 5

int object 2

This is a heap for storing objects

Space required for the main function

j: i:

Space required for the max function

result: num2:

num1:

stack

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 it up into 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: 45Enter Rate: 10 Pay: 475.0

475 = 40 * 10 + 5 * 15

Summary• Arguments• Results (fruitful

functions)• Void (non-fruitful)

functions• Why use functions?

• Functions• Built-In Functions

>Type conversion (int, float)

>String conversions• Parameters

Acknowledgements / Contributions

These slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan School of Information

… Insert new Contributors and Translators here

...