现在的位置: 首页 > 综合 > 正文

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

2012年04月13日 ⁄ 综合 ⁄ 共 4607字 ⁄ 字号 评论关闭

2-11.
带文本菜单的程序。写一个带文本菜单的程序,菜单项如下:(1)取五个数的和;(2)取五个数的平均值...(X)退出。由用户做一个选择,然后执行相应的功能。当用户选择退出时程序结束。这个程序的有用之处在于用户在功能之间切换不需要一遍一遍地重新启动你的脚本(这对开发人员测试自己的程序也会大有用处)。
【答案】
代码如下:
def to_total():
    total = 0
    a = [1, 2, 3, 4, 5]
    for i in range(0, 5):
        print 'Please input number', i+1
        a[i] = float(raw_input())
        total = total + a[i]
    print total
   
def to_average():
    total = 0
    a = [1, 2, 3, 4, 5]
    for i in range(0, 5):
        print 'Please input number', i+1
        a[i] = float(raw_input())
        total = total + a[i]
    print total / 5.
   

print 'Please select ... \n'
print '(1) To get the total of 5 numbers, please input letter "a" ... '
print '(2) To get the average of 5 numbers, please input letter "b" ... '
print '(x) To quit, please input letter "x" ... \n'
choice = raw_input('Your choice is ... ')
if choice == 'a':
    to_total()
elif choice == 'b':
    to_average()
elif choice == 'x': pass
【未完】这段代码还有优化的空间,另外,也没有检查输入不是数字的情况。

2-12.
dir()内建函数。
(a)启动Python交互式解释器。通过直接键入dir()回车以执行dir()内建函数。你看到什么?显示你看到的每一个列表元素的值,记下实际值和你想象的值。
(b)你会问,dir()函数是干什么的?我们已经知道在dir后边加上一对括号可以执行dir()内建函数,如果不加括号会如何?试一试。解释器会返回给你什么信息?你认为这个信息表示什么意思?
(c)type()内建函数接收任意的Python对象作为参数并返回他们的类型。在解释器中键入type(dir),看看你得到的是什么。
(d)本练习的最后一部分,我们来瞧一瞧Python的文档字符串。通过dir.__doc__可以访问dir()内建函数的文档字符串。print dir.__doc__可以显示这个字符串的内容。许多内建函数、方法、模块及模块属性都有相应的文档字符串。我们希望你在你的代码中也要书写文档字符串,它会对使用这些代码的人提供及时方便的帮助。
【答案】
代码如下:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\root>python
Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> dir
<built-in function dir>
>>> type(dir)
<type 'builtin_function_or_method'>
>>> dir.__doc__
"dir([object]) -> list of strings\n\nIf called without an argument, return the names in the current scope.\nElse, return an alphabetized list of names comprisin
g (some of) the attributes\nof the given object, and of attributes reachable from it.\nIf the object supplies a method named __dir__, it will be used; otherwise
\nthe default dir() logic is used and returns:\n  for a module object: the module's attributes.\n  for a class object:  its attributes, and recursively the attr
ibutes\n    of its bases.\n  for any other object: its attributes, its class's attributes, and\n    recursively the attributes of its class's base classes."
>>> print dir.__doc__
dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
  for a module object: the module's attributes.
  for a class object:  its attributes, and recursively the attributes
    of its bases.
  for any other object: its attributes, its class's attributes, and
    recursively the attributes of its class's base classes.
>>>

2-13.
利用dir()找出sys模块中更多的东西。
(a)启动Python交互式解释器,执行dir()函数。然后键入import sys以导入sys模块。再次执行dir()函数以确认sys模块被正确导入。然后执行dir(sys),你就可以看到sys模块的所有属性了。
(b)显示sys模块的版本号属性及平台变量。记住在属性名前一定要加sys.,这表示这个属性是sys模块的。其中version变量保存着你使用的Python解释器版本, platform属性则包含你运行Python时使用的计算机平台信息。
(c)最后,调用sys.exit()函数。这是一种热键之外的另一种推出Python解释器的方式。
【答案】
代码如下:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\root>python
Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import sys
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_g
etframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode
', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getde
faultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_inf
o', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', '
setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']

>>> sys.version
'2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)]'
>>> sys.platform
'win32'
>>> sys.exit()

C:\Documents and Settings\root>

2-14.
操作符优先级和括号分组。重写2.4小节中print语句里的算术表达式,试着在这个表达式中添加合适的括号以便它能正常工作。
【答案】
代码如下:
>>> print -2 * 4 + 3 ** 2
1
>>> print -2 * (4 + 3) ** 2
-98
>>> print (-2 * (4 + 3)) ** 2
196
>>>

这里列出的答案不是来自官方资源,是我自己做的练习,可能有误。

 

抱歉!评论已关闭.