Unlicensed-7-PDF151-152_Haltermanpythonbook

advertisement
7.4.
12
13
14
142
PARAMETER PASSING
# Get an integer from
def user
get_int():
return int(input("Please
the
enter
an
integer:
"))
15
16
17
#
def
18
19
20
Main code to
main():
n1 = get_int()
n2 = get_int()
print("gcd(", n1,
execute
",",
n2,
")
=
",
gcd(n1,
n2),
sep="")
21
22
23
# Run
main()
the
program
The single free statement at the end:
main()
calls the main function which in turn directly calls several other functions (get_int, print, gcd, and
str). The get_int function itself directly calls int and input. In the course of its execution the gcd
function calls range. Figure 7.2 contains a diagram that shows the calling relationships among the function
executions during a run of Listing 7.7 (gcdwithmain.py).
7.4
Parameter Passing
When a client calls a function that expects a parameter, the client must pass a parameter to the function.
The process behind parameter passing in Python is simple: the function call binds to the formal parameter
the object referenced by the actual parameter. The kinds of objects we have considered so far—integers,
floating-point numbers, and strings—are classified as immutable objects. This means a programmer cannot
change the value of the object. For example, the assignment
x = 4
binds the variable named x to the integer 4. We may change x by reassigning it, but we cannot change the
integer 4. Four is always four. Similarly, we may assign a string literal to a variable, as in
word = 'great'
but we cannot change the string object to which word refers. If the client's actual parameter references
an immutable object, the function's activity cannot affect the value of the actual parameter. Listing 7.8
(parampassing.py) illustrates the consequences of passing an immutable type to an function.
Listing 7.8: parampassing.py
1
2
def
3
4
increment(x):
print("Beginning execution of increment, x =", x)
x += 1
#
Increment x
print("Ending execution of increment, x =", x)
5
6
7
8
9
10
def
main():
x = 5
print("Before increment, x =", x)
increment(x)
print("After increment, x =", x)
©2011 Richard L. Halterman
Draft date: November 13, 2011
7.4.
143
PARAMETER PASSING
main
get_int
input
int
get_int
input
int
gcd
range
print
11
12
main()
For additional drama we chose to name the actual parameter the same as the formal parameter, but,
of course, the names do not matter because they represent completely different contexts.
(parampassing.py) produces
Listing 7.8
Before increment, x = 5
Beginning execution of increment, x = 5
Ending execution of increment, x = 6
After increment, x = 5
The variable x in main is unaffected by increment because x references an integer, and all integers are
immutable.
©2011 Richard L. Halterman
Draft date: November 13, 2011
Pr o gr am Exe cu t i o n
(Ti m e )
Figure 7.2: Calling relationships among functions during the execution of Listing 7.7 (gcdwithmain.py)
Download