Top Banner
2002 Prentice Hall. All rights reserved. 1 Functions • Purpose Building blocks for the program (separate functionality in independant parts) Avoid code repetition Calling/invoking a function functionName ( argument1, argument2 ) • Details Variables created in a function are local to that function Arguments/parameters are additional information the function needs to compete its task Arguments are also local variables The return value is information that the function returns to the source that invoked it for use elsewhere in the program
37

2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

1

Functions

• Purpose– Building blocks for the program (separate functionality in

independant parts)– Avoid code repetition

• Calling/invoking a function– functionName ( argument1, argument2 )

• Details– Variables created in a function are local to that function– Arguments/parameters are additional information the

function needs to compete its task– Arguments are also local variables– The return value is information that the function returns to

the source that invoked it for use elsewhere in the program

Page 2: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

2

4.4 Module math and its functions

• Module– Contains useful function definitions and other elements

• All of which are related in some way

– The import keyword is used to include a module

– Invoking functions from a module• Use the module name followed by the dot operator (.)• moduleName.functionName( argument )

Page 3: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

3

4.4 Module math Functions

2.3 (#1, Aug 4 2003, 10:37:16)

[GCC 3.1.1] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>>

>>> print sqrt( 900 )

Traceback (most recent call last):

File "<stdin>", line 1, in ?

NameError: name 'sqrt' is not defined

>>>

>>> import math

>>>

>>> print math.sqrt( 900 )

30.0

>>>

>>>

Fig. 4.2 Function sqrt of module math.

Page 4: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

4

4.4 Module math Functions

Method Description Example

acos( x ) Trigonometric arc cosine of x (result in radians)

acos( 1.0 ) is 0.0

asin( x ) Trigonometric arc sine of x (result in radians)

asin( 0.0 ) is 0.0

atan( x ) Trigonometric arc tangent of x (result in radians)

atan( 0.0 ) is 0.0

ceil( x ) Rounds x to the smallest integer

not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) Trigonometric cosine of x

(x in radians)

cos( 0.0 ) is 1.0

exp( x ) Exponential function ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906

fabs( x ) Absolute value of x fabs( 5.1 ) is 5.1 fabs( -5.1 ) is 5.1

floor( x ) Rounds x to the largest integer not

greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

fmod(x,y ) Remainder of x/y as a floating point number

fmod( 9.8, 4.0 ) is 1.8

Page 5: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

5

4.4 Module math Functions

hypot( x, y )

hypotenuse of a triangle with sides

of length x and y: sqrt( x2 + y

2 )

hypot( 3.0, 4.0 ) is 5.0

log( x ) Natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0

log10( x ) Logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0

pow( x, y )

x raised to power y (xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, .5 ) is 3.0

sin( x ) trigonometric sine of x

(x in radians)

sin( 0.0 ) is 0.0

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0

tan( x ) trigonometric tangent of x

(x in radians)

tan( 0.0 ) is 0.0

Fig. 4.3 math module functions.

Page 6: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

6

4.5 Function Definitions

• Definitions– Functions must be defined before they are used– def functionName ( paramList ):

• functionName is a valid identifier (legal name)

• paramList is a comma separated list of parameters received

• The actions of the function then follows

– They should all be indented appropriately

– The actions are also called the block or the function body

Page 7: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

7

Fig04_04.py

Program Output

1 # Fig. 4.4: fig04_04.py2 # Creating and using a programmer-defined function.3 4 # function definition5 def square( y ):6 return y * y7 8 for x in range( 1, 11 ):9 print square( x ),10 11 print

 1 4 9 16 25 36 49 64 81 100

This is a function definition, the function is called square and is passed the value y

The function returns the passed value multiplied by itself

This calls the square function and passes it the value x

Page 8: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

8

Fig04_05.py

1 # Fig. 4.5: fig04_05.py2 # Finding the maximum of three integers.3 4 def maximumValue( x, y, z ):5 maximum = x6 7 if y > maximum:8 maximum = y9 10 if z > maximum:11 maximum = z12 13 return maximum14 15 a = int( raw_input( "Enter first integer: " ) )16 b = int( raw_input( "Enter second integer: " ) )17 c = int( raw_input( "Enter third integer: " ) )18 19 # function call20 print "Maximum integer is:", maximumValue( a, b, c ) 21 print # print new line22 23 d = float( raw_input( "Enter first float: " ) )24 e = float( raw_input( "Enter second float: " ) )25 f = float( raw_input( "Enter third float: " ) )26 print "Maximum float is: ", maximumValue( d, e, f )27 print28 29 g = raw_input( "Enter first string: " )30 h = raw_input( "Enter second string: " )31 i = raw_input( "Enter third string: " )32 print "Maximum string is: ", maximumValue( g, h, i )

This is a function that receives three values

The function determines the greater of three values and returns it

Gets three integers, passes them to the maximumValue function, and displays the results to the user

The same process is performed on float and string variables to show the diversity of the function

Note: only possible because of dynamic typing! Function parameters not type declared

Page 9: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

9

Fig04_05.pyProgram Output

 Enter first integer: 27Enter second integer: 12Enter third integer: 36Maximum integer is: 36 Enter first float: 12.3Enter second float: 45.6Enter third float: 9.03Maximum float is: 45.6 Enter first string: helloEnter second string: programmingEnter third string: goodbyeMaximum string is: programming

Page 10: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

10

Intermezzo

1. Write a program using two for loops which calculates the length of the hypothenuse h (see figure) in all right triangles where a and b range from 6 up to and including 10.

– Use the hypot function (see page 123) from the math module (remember to import the module).

The output might look like this:

sides 6 and 6: hypothenuse 8.485281sides 6 and 7: hypothenuse 9.219544sides 6 and 8: hypothenuse 10.000000sides 6 and 9: hypothenuse 10.816654..

2. Use continue to skip cases where a = b3. Format the output so that commas appear

over each other and only 2 digits follow.

a

b

h

Page 11: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

11

solution

import math

for a in range(6, 11):

for b in range(6, 11):

if a == b:

continue

h = math.hypot(a, b)

print "sides %2d and %2d: hypothenuse %6.2f" %(a, b, h)

Page 12: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

12

4.6 Random-Number Generation

• The random module– Used to generate a random number

– Function randrange(arg1, arg2)• Generates a number from the first argument up to, but not

including, the second argument

• Each number in the range has the same likelihood of being selected by the function

Page 13: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

13

Fig04_06.py

Program Output

1 # Fig. 4.6: fig04_06.py2 # Random integers produced by randrange.3 4 import random5 6 for i in range( 1, 21 ): # simulates 20 die rolls7 print "%10d" % ( random.randrange( 1, 7 ) ),8 9 if i % 5 == 0: # print newline every 5 rolls10 print

  5 3 3 3 2 3 2 3 3 4 2 3 6 5 4 6 2 4 1 2

As shown by the output the number range is really from 1 to 6 not 7

The random module is imported

The , puts in a space instead of a newline

Page 14: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

14

Fig04_07.py

1 # Fig. 4.7: fig04_07.py2 # Roll a six-sided die 6000 times.3 4 import random5 6 frequency1 = 07 frequency2 = 08 frequency3 = 09 frequency4 = 010 frequency5 = 011 frequency6 = 012 13 for roll in range( 1, 6001 ): # 6000 die rolls14 face = random.randrange( 1, 7 )15 16 if face == 1: # frequency counted17 frequency1 += 118 elif face == 2:19 frequency2 += 120 elif face == 3:21 frequency3 += 122 elif face == 4:23 frequency4 += 124 elif face == 5:25 frequency5 += 126 elif face == 6:27 frequency6 += 128 else: # simple error handling29 print "should never get here!"30

This nested if is used to keep track of the occurrence of each number generated

Creates a loop that executes 6000 times

This else statement should never be used by the program but is there for good programming purposes

Page 15: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

15

Fig04_07.py

Program Output

31 print "Face %13s" % "Frequency"32 print " 1 %13d" % frequency133 print " 2 %13d" % frequency234 print " 3 %13d" % frequency335 print " 4 %13d" % frequency436 print " 5 %13d" % frequency537 print " 6 %13d" % frequency6

Face Frequency 1 946 2 1003 3 1035 4 1012 5 987 6 1017

Displays the total amount of times each number was returned

Page 16: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

16

4.7 Example: the dice game Craps

• A player rolls two dice. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw, the player loses (i.e. the ‘house’ wins). Otherwise, the sum is the player’s ‘point’.

• To win, the player must continue to roll the dice until he makes his point again. If he rolls 7 before that, he loses.

Page 17: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

17

Fig04_08.py

1 # Fig. 4.8: fig04_08.py2 # Craps.3 4 import random5 6 def rollDice():7 die1 = random.randrange( 1, 7 )8 die2 = random.randrange( 1, 7 )9 workSum = die1 + die210 print "Player rolled %d + %d = %d" % ( die1, die2, workSum )11 12 return workSum13 14 sum = rollDice() # first dice roll15 16 if sum == 7 or sum == 11: # win on first roll17 gameStatus = "WON"18 elif sum == 2 or sum == 3 or sum == 12: # lose on first roll19 gameStatus = "LOST"20 else: # remember point21 gameStatus = "CONTINUE"22 myPoint = sum23 print "Point is", myPoint24 25 while gameStatus == "CONTINUE": # keep rolling26 sum = rollDice()27 28 if sum == myPoint: # win by making point29 gameStatus = "WON"30 elif sum == 7: # lose by rolling 7:31 gameStatus = "LOST"32 33 if gameStatus == "WON":34 print "Player wins"35 else:36 print "Player loses"

The start of the rollDice function

Prints out the value of each random number along with their sum, which is also returned

An if statement that determines the next step in the game based on what the player rolled

The while statement will loop until the player has wither lost or won the game (using CONTINUE as a sentinel value)

Page 18: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

18

Fig04_08.py

Program OutputPlayer rolled 2 + 5 = 7Player wins

Player rolled 1 + 2 = 3Player loses

Player rolled 1 + 5 = 6Point is 6Player rolled 1 + 6 = 7Player loses

Player rolled 5 + 4 = 9Point is 9Player rolled 4 + 4 = 8Player rolled 2 + 3 = 5Player rolled 5 + 4 = 9Player wins

Page 19: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

19

4.8 Scope Rules

• Rules for retrieving a variable’s value– Based on namespaces and scope

– Namespaces store information about identifiers and the values to which they are bound

– Three types• Local, global, and built-in

• They are checked by Python in that order

• Local namespace– Contains variables that were created in a block

– Thus, each function has a unique local namespace

Page 20: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

20

4.8 Scope Rules

• Global namespace– Stores the names of functions and classes defined within the

file or module

– Each module contains an identifier __name__• It holds the name of the module (“math”) or “__main__”

(we’ll see how that can be used)

• Built-in namespace– Contains functions such as raw_input, int, and range– The built-in namespace is included when the interpreter

starts (thus we automatically have access to these functions)

Page 21: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

21

Function dir()>>>

>>> dir()

['__builtins__', '__doc__', '__name__']

>>>

>>> print __name__

__main__

>>>

>>> x = 3

>>> dir()

['__builtins__', '__doc__', '__name__', 'math', 'x']

>>>

>>>

>>> dir(__builtins__)

['ArithmeticError', 'AssertionError', 'AttributeError',..

.. 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', ..

built-in function dir() lists the identifiers in the current namespace

Since this is not a module (but rather an interactive session), the value of __name__ is __main__

dir(__builtins__) lists identifiers in the __builtins__ module

new global variable

Page 22: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

22

Fig04_10.py

1 # Fig. 4.10: fig04_10.py2 # Scoping example.3 4 x = 1 # global variable5 6 # alters the local variable x, shadows the global variable7 def a(): 8 x = 259 10 print "\nlocal x in a is", x, "after entering a"11 x += 112 print "local x in a is", x, "before exiting a"13 14 # alters the global variable x15 def b():16 global x17 18 print "\nglobal x is", x, "on entering b"19 x *= 1020 print "global x is", x, "on exiting b"21 22 print "global x is", x23 24 x = 725 print "global x is", x26 27 a()28 b()29 a()30 b()31 32 print "\nglobal x is", x

This is a global variable and can be used by any function in the program

Changes the value of x to 7

Has its own value of x therefore the global value is hidden

Function b uses and modifies the value of the global x (keyword global)

Page 23: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

231 # Fig. 4.10: fig04_10.py2 # Scoping example.3 4 x = 1 # global variable5 6 # alters the local variable x, shadows the global variable7 def a(): 8 x = 259 10 print "\nlocal x in a is", x, "after entering a"11 x += 112 print "local x in a is", x, "before exiting a"13 14 # alters the global variable x15 def b():16 global x17 18 print "\nglobal x is", x, "on entering b"19 x *= 1020 print "global x is", x, "on exiting b"21 22 print "global x is", x23 24 x = 725 print "global x is", x26 27 a()28 b()29 a()30 b()31 32 print "\nglobal x is", x

global x is 1global x is 7 local x in a is 25 after entering alocal x in a is 26 before exiting a global x is 7 on entering bglobal x is 70 on exiting b local x in a is 25 after entering alocal x in a is 26 before exiting a global x is 70 on entering bglobal x is 700 on exiting b global x is 700

Page 24: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

24

4.9.1 Importing One or More Modules

• Importing– Use the keyword import followed by the desired module

– Inserts the imported module into the program’s namespace• Several imports may be made over several lines

• One import can exist with several comma separated modules

Page 25: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

25

4.9.1 Importing One or More Modules

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> >>> import math>>> dir()['__builtins__', '__doc__', '__name__', 'math']>>> >>> print math<module 'math' (built-in)>>>> >>> dir( math )['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh','e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10','modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']>>> >>> math.sqrt( 9.0 )3.0

Fig. 4.11 Importing a module.

• identifier math now points to a module

• dir(math) lists all identifiers in the math module

Page 26: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

26

4.9.2 Importing Identifiers as a Module

• The from/import statement– Allows a programmer to import only a specific part of a

module

– Takes identifiers from a module and inserts them directly into the current program’s name space (avoids e.g. math. prefix)

Page 27: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

27

4.9.2 Importing Identifiers as a Module

>>> from math import sqrt>>>>>> dir()['__builtins__', '__doc__', '__name__', 'sqrt']>>>>>> sqrt( 9.0 )3.0>>>>>> from math import sin, cos, tan>>>>>> dir()['__builtins__', '__doc__', '__name__', 'cos', 'sin', 'sqrt', 'tan']

Fig. 4.13 Importing an identifier from a module.

Now directly a part of the current namespace

Page 28: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

28

4.9.2 Importing Identifiers as a Module

>>> from math import *>>>>>> dir()['__builtins__', '__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp','log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

Fig. 4.14 Importing all identifiers from a module.

Danger! What if you already have a log() function with a different purpose (perhaps you are a captain and wrote the function to access your ship’s log..)?

Either just import math and use math.log(), or ..

Page 29: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

29

Binding new names to modules and module functions

• from <module> import <name> as <newname>– imports a function but gives it a different name:

from math import log as logarithm

• You can also give a new name to an entire module:– import math as mathtoolbox

Page 30: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

30

4.9.3 Binding Names of Modules as Module Identifiers

 >>> import random as randomModule>>>>>> dir()['__builtins__', '__doc__', '__name__', 'randomModule']>>>>>> randomModule.randrange( 1, 7 )1>>>>>> from math import sqrt as squareRoot>>>>>> dir()['__builtins__', '__doc__', '__name__', 'randomModule', 'squareRoot']>>>>>> squareRoot( 9.0 )3.0

Fig. 4.15 Specifying names for imported elements.

Page 31: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

39

4.13 Default Arguments

A function may sometimes be called repeatedly with

the same values– When this is true default arguments can be set

• Must appear to the right of any other arguments in the function definition’s argument list:

def myfunction( a, b = 2, c = 3 ):• Given values are ‘filled in from the left’ (resolves ambiguity)

myfunction(6, 3) # set a and b, use default for c

myfunction(6) # set a, use default for b and c

– A default value can also be overridden:

myfunction(6, 3, 7) # overrides default c value

Page 32: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

40

Fig04_20.py

Program Output

1 # Fig. 4.20: fig04_20.py2 # Using default arguments.3 4 # function definition with default arguments5 def boxVolume( length = 3, width = 2, height = 1 ):6 return length * width * height7 8 print "The default box volume is:", boxVolume()

9 print "\nThe volume of a box with length 10,"10 print "width 2 and height 1 is:", boxVolume( 10 )

11 print "\nThe volume of a box with length 10,"12 print "width 5 and height 1 is:", boxVolume( 10, 5 )

13 print "\nThe volume of a box with length 10,"14 print "width 5 and height 2 is:", boxVolume( 10, 5, 2 )

The default box volume is: 6 The volume of a box with length 10,width 2 and height 1 is: 20 The volume of a box with length 10,width 5 and height 1 is: 50 The volume of a box with length 10,width 5 and height 2 is: 100

Sets the three values to 1 by default

All default values used

The 10 will replace the left-most 1 and the other default values will be used

No default values used

Here two values are sent replacing the two left-most default values

Page 33: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

41

4.14 Keyword Arguments

• Keyword arguments– You can use argument names as keywords:

– Allows arguments to be passed in any order so long as they are explicitly stated:

def myfunction( a = 2, b = 3 ):

..

myfunction ( b = 5, a = 9 )

– Will use default values for those arguments that were not given by keyword:

myfunction ( b = 5 ) # use a=2

Page 34: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall.All rights reserved.

42

Program Output

# keyword example

def generatePerson( name, age = 53, job = “president", country = "US“ ):

print "Personal data: %s, %d, %s (%s)" %(name, age, job, country) print

generatePerson("George")

generatePerson("Tony", country = "GB", job = "prime minister")

generatePerson(age = 92, name = "Ronald")

Personal data: George, 53, president (US)

Personal data: Tony, 53, prime minister (GB)

Personal data: Ronald, 92, president (US)

Sets the first argument and uses the defaults for all the others

Some of the arguments have default values

The arguments are given new values except age which uses the default. Values need not be entered in order.

name can be used as keyword as well, even though it doesn’t have a default value

Page 35: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

43

4.14 Keyword Arguments

>>>>>> def test( name, number1 = 10, number2 = 20 ):... pass...>>> test( number1 = 30, “George" )SyntaxError: non-keyword arg after keyword arg>>>>>>>>> test( number1 = 30 )Traceback (most recent call last): File "<stdin>", line 1, in ?TypeError: test() takes at least 1 non-keyword argument (0 given)

 Fig. 4.22 Errors with keyword arguments.

Keyword arguments must appear to the right of any other arguments in a function call.

Keyword argument number1 given before the name (not given by keyword)

No value given for name which doesn’t have a default value

Page 36: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

44

Intermezzo

1. Copy and run fig04_07.py (see page 128) from: ~chili/CSS.E03/Programs_from_book/ch04/fig04_07.py

2. Change line 14 to face = honestDie() and write the function honestDie which returns a random number between 1 and 6.

3. Write another function, cheatingDie, which returns 6 with probability 0.25 (and 1 - 5 with probabilities 0.15). Call this function 60000 times (instead of 6000) and check that the frequencies change.

4. Change cheatingDie so it takes an argument 0 < p < 1 and returns 6 with probability p and each of the other numbers with probability (1 - p)/5

Page 37: 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.

2002 Prentice Hall. All rights reserved.

45

solutiondef honestDie():

return random.randrange( 1, 7 )

def cheatingDie25():

if random.randrange( 1, 5 ) == 1: # Return 6 with probability 1/4

return 6

else:

return random.randrange( 1, 6 ) # Return a random number between 1 and 5

def cheatingDie( p ):

p *= 100 # Now p is a number between 0 and 100

if random.randrange( 1, 101 ) <= p:

return 6

else:

return random.randrange( 1, 6 )

..

for roll in range( 1, 60001 ): # 60000 die rolls

face = cheatingDie(.50)

# face = cheatingDie25()

# face = honestDie()

..