《Python核心编程》第二版第308页第十一章练习 续五 -Python核心编程答案-自己做的-

本博客列出的答案不是来自官方资源,是我自己做的练习,如果有疑问或者错误,欢迎讨论。

11-18.
同步化函数调用。复习一下第6章中当引入浅拷贝和深拷贝的时候,提到的丈夫和妻子情形(6.20小结)。他们共用了一个普通账户,同时对他们银行账户访问时会发生不利影响。创建一个程序,让调用改变账户收支的函数必须同步。
【未完】
目前感觉本题有难度,暂时押后。

 

11-19.

Variable Scope. Earlier in the chapter (see Example 11.9 on p. 466), we left determining the output of scope.py as an exercise for the reader.
(a) Write down your best guess, then download the code and run it. Were you close? Explain where you were wrong and why (if applicable). Hint: first determine the total number of lines output by counting how many print statements will execute before trying to figure out the output.
(b) Line 11 in proc2() is currently blank... insert this statement (indented properly): global j. How does this affect the output (and why)?
【注】英文版原书有本题。Example 11.9是指中文版书304页11.8.6小节的那个例子。
【答案】
(a)运行结果

j == 3 and k == 4
j == 1 and k == 7
j == 3 and k == 4
j == 6 and k == 7
j == 8 and k == 7

 

(b)运行结果

j == 3 and k == 4
j == 1 and k == 7
j == 3 and k == 4
j == 6 and k == 7
j == 6 and k == 7
 
#本文来自博客园balian
*** *** *** ***

【例子源码】

Example 11.9 Variable Scope (scope.py)

 

j, k = 1, 2

def proc1():
    j, k = 3, 4
    print "j == %d and k == %d" % (j, k)
    k = 5

def proc2():
    #global j
    j = 6
    proc1()
    print "j == %d and k == %d" % (j, k)


k = 7
proc1()
print "j == %d and k == %d" % (j, k)

j = 8
proc2()
print "j == %d and k == %d" % (j, k)

 

***   ***   ***   ***

keyword Python核心编程答案

你可能感兴趣的:(python)