《Python核心编程》第二版第36页第二章练习


2.21 练习

2-1.
变量,print和字符串格式化操作符。启动交互式解释器,给一些变量赋值(字符串,数值等)并通过输入变量名显示他们的值。再用print语句做同样的事。这两者有何区别?也尝试着使用字符串格式操作符%,多做几次,慢慢熟悉它。
【答案】
对于一个字符串,在仅使用变量名时,输出的字符串是用单引号括起来了的。这是为了让非字符串对象也能以字符串的方式显示在屏幕上,即它显示的是该对象的字符串表示,而不仅仅是字符串本身。如果使用print命令,能使输出更加友好。

2-2.
程序输出。阅读下面的Python脚本。
#!/usr/bin/env python
1 + 2 * 4
(a)你认为这段脚本是用来做什么的?
(b)你认为这段脚本会输出什么?
(c)输入以上代码,并保存为脚本,然后运行它,它所做的与你的预期一样吗?为什么一样/不一样?
(d)这段代码单独执行和在交互解释器中执行有何不同?试一下,然后写出结果。
(e)如何改进这个脚本,以便它能和你想象的一样工作?
【答案】
用来计算。
会输出9,如果是在WINDOWS系统和Ubuntu系统。
如果仅仅是以上代码的脚本,是没有输出的。
在交互解释器中执行以后得到结果9。
如果需要将其在脚本中执行并得到期望结果,需要改成 print 1 + 2 * 4 即可。

2-3.
数值和操作符。启动交互解释器,使用Python对两个数值(任意类型)进行加、减、乘、除运算。然后使用取余操作符来得到两个数相除的余数,最后使用乘方操作符求A数的B次方。
【答案】
略。
请注意Python的除法,在3.0以下的版本中,有所谓True除法和地板除。
当使用x/y形式进行除法运算时,如果x和y都是×××,那么运算的会对结果进行截取,取运算的整数部分。
>>> print 5 / 3
1
如果x和y中有一个是浮点数,那么会进行True除法。
>>> print 5 / 3.
1.66666666667
所谓floor除法,采用x//y的形式,得到不大于结果的最大整数值,这个运算时与操作数无关的。
>>> print -5 // 3
-2
>>> print -5 // 3.
-2.0

2-4.
使用raw_input()函数得到用户输入。
(a)创建一段脚本使用raw_input()内建函数从用户输入得到一个字符串,然后显示这个用户刚刚键入的字符串。
(b)添加一段类似的代码,不过这次输入的是数值。将输入数据转换为一个数值对象,(使用int()或其他数值转换函数)并将这个值显示给用户看(注意,如果你用的是早于1.5的版本,你需要使用string.ato*()函数执行这种转换)。
【答案】
(a)代码如下:
>>> a = raw_input("Please input a string ... ")
Please input a string ... 99
>>> print a
99
(b)代码如下:
>>> a = raw_input("Please input a letter ... ")
Please input a letter ... b
>>> print ord(a)
98

2-5.
循环和数字。分别使用while和for创建一个循环。
(a)写一个while循环,输出整型为0~10(要确保是0~10,而不是0~9或1~10)。
(b)做同(a)一样的事,不过这次使用range()内建函数。
【答案】
(a)for循环代码如下:
>>> for i in 'abcdefghijk':
...     print ord(i)-97,
...
0 1 2 3 4 5 6 7 8 9 10
(a)while循环代码如下:
>>> i = 0
>>> while ( i < 11 ):
...     print i,
...     i = i + 1
...
0 1 2 3 4 5 6 7 8 9 10
(b)代码如下:
>>> for i in range(0,11):
...     print i,
...
0 1 2 3 4 5 6 7 8 9 10



2-6.
条件判断。判断一个数是正数还是负数,或者是0。开始先用固定的数值,然后修改你的代码支持用户输入数值再进行判断。
【答案】
代码如下:
a = float(raw_input("Please input a number ... "))
if a == 0:
    print "The number you input is Zero"
elif a > 0:
    print "The number you input is Positive"
else:
    print "This is a negative number"

2-7.
循环和字串。从用户那里接受一个字符串输入,然后逐字符显示该字符串。先用while循环实现,然后再用for循环实现。
【答案】
代码如下:
a = raw_input("Please input a string ... ")
print 'Display in for loop:'
for i in a:
    print i,
print '\nDisplay in while loop:'
j = 0
while (j < len(a)):
    print a[j]
    j = j + 1

2-8.
循环和操作符。创建一个包含五个固定数值的列表或元组,输出他们的和。然后修改你的代码为接受用户输入数值。分别使用while和for循环实现。
【答案】
代码如下:
# Using while loop
i = 0
total = 0
a = [1, 2, 3, 4, 5]
while (i < 5):
    print 'Please input number', i+1
    a[i] = float(raw_input())
    total = total + a[i]
    i = i + 1
print 'The total is', total

# Using for loop
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 'The total is', total

2-9.
循环和操作符。创建一个包含五个固定数值的列表或元组,输出他们的平均值。本练习的难点之一是通过除法得到平均值。你会发现整型除会截去小数,因此你必须使用浮点除以得到更精确的结果。float()内建函数可以帮助你实现这一功能。
【答案】
代码如下:
i = 0
total = 0
a = [1, 2, 3, 4, 5]
while (i < 5):
    print 'Please input number', i+1
    a[i] = float(raw_input())
    total = total + a[i]
    i = i + 1
print 'The average is', total / 5.

# Using for loop
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 'The average is', total / 5.

2-10.
带循环和条件判断的用户输入。使用raw_input()函数来提示用户输入一个1和100之间的数,如果用户输入的数值满足这个条件,显示成功并退出。否则显示一个错误信息然后再次提示用户输入数值,直到满足条件为止。
【答案】
代码如下:
t = 1
while (t):
    a = float(raw_input('Please input a number between 1 and 100: ... '))
    if a < 100 and a > 1:
        print 'Your have input a number between 1 and 100.'
        t = 0
    else:
        print 'Please try again ...'


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
>>>


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

for i in range(0,3):
    print 'Please input the No.', i+1, 'number to be sort'
    SortList[i] = float(raw_input())
print SortList
 
if SortList[0] < SortList[1]:
    i = SortList[0]
    SortList[0] = SortList[1]
    SortList[1] = i

if SortList[0] < SortList[2]:
    i = SortList[0]
    SortList[0] = SortList[2]
    SortList[2] = i
   
if SortList[1] < SortList[2]:
    i = SortList[1]
    SortList[1] = SortList[2]
    SortList[2] = i
    
print SortList
【注】这段代码是从大到小排序,如果想修改成从小到大,把小于号换成大于号就可以了。


2-16.
文件。键入2.15节的文件显示的代码,然后运行它。看看能否在你的系统上正常工作。然后试一下其他的输入文件。
【答案】
代码如下:
>>> filename = raw_input('Enter file name: ')
Enter file name: c:\test.txt
>>> fobj = open(filename, 'r')
>>> for eachLine in fobj:
...     print eachLine,
...
This is an apple.
>>> fobj.close()
>>>
【注】这里假设有一个名为test.txt的文件在C盘的根目录下。