33
Function and Function call Functions name programs Functions can be defined: def myFunction(<parameter names>): function body (indented) Functions can be called: myFunction(<parameter values>) The number of arguments is fixed; could be zero The function returns a value; could be None

Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Embed Size (px)

DESCRIPTION

Function Call as Substitution When a function is called The argument values are bound (assigned) to the parameter names The program of the function is executed as if those program statements were substituted for the call Upon execution of the return statement, the return value is substituted for the function call If no return statement is executed, and the program of the function body ends, the function returns None, indicating that no value is returned to the calling place.

Citation preview

Page 1: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Function and Function callFunctions name programs

Functions can be defined:def myFunction(<parameter names>): function body (indented)

Functions can be called:myFunction(<parameter values>)

The number of arguments is fixed; could be zeroThe function returns a value; could be None

Page 2: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Function OutputThe return statement specifies what value the

function returns to the call site: return <expression>

Return StatementPassing a value out of a function (output)Last statement executedMultiple conditional exit possible

Page 3: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Function Call as Substitution

When a function is calledThe argument values are bound (assigned) to the

parameter namesThe program of the function is executed as if those

program statements were substituted for the callUpon execution of the return statement, the return

value is substituted for the function call If no return statement is executed, and the

program of the function body ends, the function returns None, indicating that no value is returned to the calling place.

Page 4: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Examplex = 12y = 4def mySum(a,b): u = a+b x = 1 return uprint(x,y)print(mySum(x,y))print(x,y)

Unless explicitly declared global,x is a local variable

Page 5: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

More on ReturnsReturns are the last statement executed by a

functionThe function is considered to be “done” at this

pointThere may be other statements “after” the

return, but these are not executed (but see conditionals later-on

def sumOfTwo(a,b):return a+bprint(a+b)print(a+b)

print(sumOfTwo(4,5))

Page 6: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Stringing together functions

We can build up complex expressions from functions

def sumOfTwo(a,b):return a+b

print(sumOfTwo(sumOfTwo(4,5), sumOfTwo(1,2)))

OR

a = sumOfTwo(4,5)b = sumOfTwo(1,2)c = sumOfTwo(a,b)print(c)

Page 7: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Local VariablesFunction parameter names act as local

variables:They are available as variables for the execution of

the function bodyThey get their initial value from the values at the

call site (value binding)When the function ends, they are no longer

availableYou can define additional variables in the

function bodyThey will be local variables by defaultWhen the function ends, they no longer exist

Page 8: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Local Variablesa = 3y = 10def myFun(a): print (a) y = 1myFun(4)print(a)print(y)

Page 9: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Question: does this program print 3 or 4?x = 3def myFun(): print (x)x = 4myFun()

(a) 3

(b) 4

Page 10: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Are these programs equivalent?#1a = 3def myFun(a): print (a)myFun(4)

#2a = 3print (a) (a) Yes

(b) No

Page 11: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Variables and FunctionsVariables defined outside of the function are

global variablesGlobal variables can be changed inside a function

bodyUsing global variables inside functions is

dangerous:Multiple calls to a function may yield different results

if the program “rebinds” such variables

At minimum, declare global variables as global in the function body and document their use.

Page 12: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Variables and Functionsx = 3def myFun(): print (x)x = 4myFun()x =5myFun()

Page 13: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

You must be careful!x = 3def myFun(): print (x) x = 1x = 4myFun()x =5myFun()

ERROR!

ERROR!

Page 14: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Global VariablesHow can we get the example code we saw

earlier to work?Python is not sure if we want x to be a local

variable or if it should refer to the x we defined outside of the function

We can inform python if we want x to refer to the variable outside of the functionNew keyword global

Page 15: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

This works!x = 3def myFun(): global x print (x) x =1x = 4myFun()myFun()

Page 16: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Global or Local?If the global keyword is used, the variable is

globalIf the first use of the variable is a ‘read’

(reference), the variable is globalNOTE: We cannot assign to such a variable laterFunction arguments are always local

If the first use of the variable is a write (assignment), the variable is localUnless the variable is defined global

Page 17: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Clicker Question: Is x global or local?

x = 3def myFun(): y = 4 z = x + ymyFun()

A: global

B: local

Page 18: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Let’s ReviewFunctions take input and produce outputOutput is provided by the “return” statement

Otherwise the function does not provide output

At the call site of the function the arguments get boundThe arguments can rebind variables that have already

been defined for the duration of the call

You can use global variables, defined outside the function, but you must be careful!

Page 19: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

AdviceUnless absolutely necessary avoid naming

parameters and local variables the same as global variables

Page 20: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Argument TypingFunctions typically assume something important

about the arguments

Will this work no matter what we provide as arguments?

def sumOfTwo(a,b):return a+b

Page 21: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Function ArgumentsConsider the following three cases:

One of these cases will throw an error. This behavior is defined by the code inside the function

res = sumOfTwo(1,2)res = sumOfTwo(“Hello “, “World”)res = sumOfTwo(“Hello”, 1)

Page 22: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Function ArgumentsThere are two ways to handle this difficulty

1. Tell everyone what the function expects2. Include checks inside the function to ensure the

arguments are what is expected

A combination of both techniques should be used

Page 23: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Function DocumentationThis solution uses comments and if-statements.We will revisit this in later slides

# This function expects two integers # and returns -1 otherwisedef sumOfTwo(a,b):

if type(a) == int and type(b) == int : return a+b

return -1

Page 24: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

Suppose you are writing a program that manages bank accounts. One function we would need to do is to accumulate interest on the account. Let’s look at a first-cut at the function.

def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance

Page 25: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

The intent is to set the balance of the account to a new value that includes the interest amount.

Let’s write a main program to test this:def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount)

Page 26: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

We hope that that the 5% will be added to the amount, returning 1050.

>>> test()1000

What went wrong? Nothing!

Page 27: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

The first two lines of the test function create two local variables called amount and rate which are given the initial values of 1000 and 0.05, respectively.

def addInterest(balance, rate):

newBal = balance*(1+rate) balance = newBaldef test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount)test()

Page 28: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

The first two lines of the test function create two local variables called amount and rate which are given the initial values of 1000 and 0.05, respectively.

def addInterest(balance, rate):

newBal = balance*(1+rate) balance = newBaldef test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount)test()

Page 29: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

def addInterest(balance, rate):

newBalance = balance * (1 + rate)

return newBalance

def test():

amount = 1000

rate = 0.05

addInterest(amount, rate)

print(amount)

test()

Page 30: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

def addInterest(balance, rate):

newBalance = balance * (1 + rate)

return newBalance

def test():

amount = 1000

rate = 0.05

amount = addInterest(amount, rate)

print(amount)

test()

Page 31: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Functions that Modify Parameters

Why is the following solution inferior?

amount = 1000 rate = 0.05 def addInterest(): global amount global rate

amount = amount * (1 + rate) addInterest() print(amount)

Page 32: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Libraries What is the difference between:

1. import library2. from library import *

Both provide you with a mechanism to utilize additional functionality in your program Version 1 requires referencing library functions using the object notation:

<library>.<function>(<parameters>) import math math.sqrt(x)

Version 2 obligates you to use the function name without library reference: from math import * sqrt(x)

If you mix the two Python throws an error

Page 33: Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Libraries>>> from math import *>>> math.sqrt(4)Traceback (most recent call last): File "<pyshell#153>", line 1, in <module> math.sqrt(4)NameError: name 'math' is not defined

>>> import graphics >>> win = GraphWin() Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> win = GraphWin() NameError: name 'GraphWin' is not defined