zoukankan      html  css  js  c++  java
  • Python核心编程(第二版) 第二章习题答案

    2-9.循环和操作符。创建一个包含五个固定数值的列表或元组,输出他们的平均值。本练习的难点之一是通过除法得到平均值。你会发现整型除会截去小数,因此你必须使用浮点除以得到更精确的结果。float()内建函数可以帮助你实现这一功能。

    答:

     1 #!/usr/bin/python
     2 '''receive 5 nums and average them'''
     3 
     4 summ=0
     5 li=[]
     6 for i in range(5):
     7     a=float(raw_input("Enter a num:"))
     8     li.append(a)
     9     summ=summ+a
    10 
    11 div=summ/5
    12 
    13 print li
    14 print "The sum of 5 nums is %f."%summ
    15 print "The average of 5 num is %f."%div

    2-10.带循环和条件判断的用户输入。使用raw_input()函数来提示用户输入一个1和100之间的数,如果用户输入的数值满足这个条件,显示成功并退出。否则显示一个错误信息然后再次提示用户输入数值,直到满足条件为止。

    答:

     1 #!/usr/bin/python 
     2 '''guess a num'''
     3 
     4 lottery=45
     5 status=1
     6 
     7 while status:
     8     num=int(raw_input("Enter a num[1,100]:"))
     9     if 100>=num>lottery:
    10         print "It's is large."
    11     elif 1<=num<lottery:
    12         print "It's is litte."
    13     elif num>100:
    14         print "It's lager than 100."
    15     elif num<1:
    16         print "It's litter than 1."
    17     else:
    18         print "Congratulations!you got the num!"
    19         status=0

    2-11.带文本菜单的程序。写一个带文本菜单的程序,菜单项如下:(1)取五个数的和;(2)取五个数的平均值...(X)退出。由用户做一个选择,然后执行相应的功能。当用户选择退出时程序结束。这个程序的有用之处在于用户在功能之间切换不需要一遍一遍地重新启动你的脚本(这对开发人员测试自己的程序也会大有用处)。

    答:

     1 #!/usr/bin/python
     2 '''menu:1 sum of 5 num
     3     2 average of 5 num
     4     X exit'''
     5 
     6 def nsum():
     7     li=[]
     8     s=0
     9     for i in range(5):
    10         num=float(raw_input("Enter a num:"))
    11         li.append(num)
    12         s=s+num
    13     print "The sum of 5 num is %f."%s
    14 
    15 
    16 def  ndiv():
    17     li=[]
    18     s=0
    19     for i in range(5):
    20         num=float(raw_input("Enter a num:"))
    21         li.append=[num]
    22         s=s+num
    23     div=s/5
    24 
    25 
    26 print "menu"
    27 print "1.receive 5 num and then sum it."
    28 print "2.receive 5 num and then average it."
    29 print "X.exit"
    30 
    31 select=raw_input("Please input your choice:")
    32 if select=='1':
    33     nsum()
    34 elif select=='2':
    35     ndiv()
    36 elif select=='X':
    37     exit()
    38 else:
    39     print "You input a wrong choice."

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


    b.
    >>> dir
    <built-in function dir>
    >>>

    c.
    >>> type(dir)
    <type 'builtin_function_or_method'>
    >>>

    d.
    >>> 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解释器的方式。
    a.
    >>> dir()
    ['__builtins__', '__doc__', '__name__', '__package__']
    >>> import sys
    >>> dir()
    ['__builtins__', '__doc__', '__name__', '__package__', 'sys']
    >>> dir(sys)
    ['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
    >>>

    b.
    >>> sys.version
    '2.7.3 (default, Feb 27 2014, 19:58:35) [GCC 4.6.3]'
    >>> sys.platform
    'linux2'
    >>>

    c.
    >>> sys.exit()
    tmyyss@ubuntu:~$

    2-14.操作符优先级和括号分组。重写2.4小节中print语句里的算术表达式,试着在这个表达式中添加合适的括号以便它能正常工作
    答:略

    2-15.元素排序。
    (a)让用户输入三个数值并分别将它们保存到3个不同的变量中。不使用列表或排序算法,自己写代码来对三个数由小到大排序。
    (b)修改(a)的解决方案,使之从大到小排序。

    答:

     1 #!/usr/bin/python
     2 
     3 a=float(raw_input("Enter a num:"))
     4 b=float(raw_input("Enter a num:"))
     5 c=float(raw_input("Enter a num:"))
     6 
     7 if a>b:
     8     if b>=c:
     9         print '%.2f %.2f %.2f'%(a,b,c)
    10     else:
    11         if a>c:
    12             print '%.2f %.2f %.2f'%(a,c,b)
    13         else :
    14             print '%.2f %.2f %.2f'%(c,a,b)
    15 else:
    16     if b<=c:
    17         print '%.2f %.2f %.2f'%(c,b,a)
    18     else:
    19         if a<c:
    20             print '%.2f %.2f %.2f'%(b,c,a)
    21         else:
    22             print '%.2f %.2f %.2f'%(b,a,c)
    23     
     1 #!/usr/bin/python
     2 
     3 a=float(raw_input("Enter a num:"))
     4 b=float(raw_input("Enter a num:"))
     5 c=float(raw_input("Enter a num:"))
     6 
     7 if a>b:
     8     if b>=c:
     9         print '%.2f %.2f %.2f'%(c,b,a)
    10     else:
    11         if a>c:
    12             print '%.2f %.2f %.2f'%(b,c,a)
    13         else :
    14             print '%.2f %.2f %.2f'%(b,a,c)
    15 else:
    16     if b<=c:
    17         print '%.2f %.2f %.2f'%(a,b,c)
    18     else:
    19         if a<c:
    20             print '%.2f %.2f %.2f'%(a,c,b)
    21         else:
    22             print '%.2f %.2f %.2f'%(c,a,b)
    23     

    2-16.文件。键入2.15节的文件显示的代码,然后运行它。看看能否在你的系统上正常工作。然后试一下其他的输入文件。

    答:略

  • 相关阅读:
    debug和release转载
    坐标系与基本图元(8)
    坐标系与基本图元(7)
    坐标系与基本图元(5)
    坐标系与基本图元(6)
    坐标系与基本图元(4)
    坐标系与基本图元(3)
    坐标系与基本图元(2)
    BZOJ 1090
    Xor
  • 原文地址:https://www.cnblogs.com/tmyyss/p/3746554.html
Copyright © 2011-2022 走看看