文档库 最新最全的文档下载
当前位置:文档库 › python核心编程第二版第2章习题答案

python核心编程第二版第2章习题答案

python核心编程第二版第2章习题答案
python核心编程第二版第2章习题答案

2-1.变量,print和字符串格式化操作符。启动交互式解释器,给一些变量赋值(字符串,数值等)并通过输入变量名显示他们的值。再用print语句做同样的事。这两者有何区别?也尝试着使用字符串格式操作符%,多做几次,慢慢熟悉它。

答案:

对于一个字符串,在仅使用变量名时,输出的字符串是用单引号括起来了的。这是为了让非字符串对象也能以字符串的方式显示在屏幕上,即它显示的是该对象的字符串表示,而不仅仅是字符串本身。如果使用print命令,能使输出更加友好。

2-2.程序输出。阅读下面的Python脚本。

#!/usr/bin/env python

1 +

2 * 4

(a)你认为这段脚本是用来做什么的?

(b)你认为这段脚本会输出什么?

(c)输入以上代码,并保存为脚本,然后运行它,它所做的与你的预期一样吗?为什么一样/不一样?

(d)这段代码单独执行和在交互解释器中执行有何不同?试一下,然后写出结果。

(e)如何改进这个脚本,以便它能和你想象的一样工作?

答案:

(a)计算

(b)输出9

(c)不一样,不会有输出

(d)在交互解释器中可以输出9

(e)需添加一个print,即

#!/usr/bin/env python

print 1 + 2 * 4

2-3.数值和操作符。启动交互解释器,使用Python对两个数值(任意类型)进行加、减、乘、除运算。然后使用取余操作符来得到两个数相除的余数,最后使用乘方操作符求A数的B

次方。

答案:

当使用x/y形式进行除法运算时,如果x和y都是整形,那么运算的结果就是运算的整数部分。

>>> print 10 / 3

3

如果x和y中有一个是浮点数,那么会进行精确除法。

>>> print 10 / 3.0

3.33333333333

所谓地板除,采用x//y的形式,得到不大于结果的最大整数值,这个运算时与操作数无关的。

>>> 1//2

>>> 1.0//2

0.0

>>> -1//2.0

-1.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: hello world

>>> print a

hello world

(b)

>>> a = raw_input("please input a number: ")

please input a number: 123

>>> print type(a)

>>> a = int(raw_input("please input a number: "))

please input a number: 123

>>> print type(a)

2-5.循环和数字。分别使用while和for创建一个循环。

(a)写一个while循环,输出整型为0~10(要确保是0~10,而不是0~9或1~10)。(b)做同(a)一样的事,不过这次使用range()内建函数。

答案:

(a)

>>> i = 0

>>> while i < 11:

print 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 = int(raw_input("Please input a number: "))

if a > 0:

print "The number is Positive."

elif a < 0:

print "The number is negative."

else:

print "The number is Zero."

2-7.循环和字串。从用户那里接受一个字符串输入,然后逐字符显示该字符串。先用while 循环实现,然后再用for循环实现。

for循环

a = raw_input("please input a string: ")

for i in a:

print i,

while循环

a = raw_input("please input a string: ")

i = 0

while i < len(a):

print a[i],

i = i + 1

2-8.循环和操作符。创建一个包含五个固定数值的列表或元组,输出他们的和。然后修改你的代码为接受用户输入数值。分别使用while和for循环实现。

l = [1,2,3,4,5]

total = 0

for i in l:

total = total + i

print 'Total is',total

l = [1,2,3,4,5]

i = 0

total = 0

while i < len(l):

total = total + l[i]

i = i + 1

print 'Total is',total

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

答案:

total = 0

for i in range(0, 5):

print 'Please input number %d' % (i + 1)

a = float(raw_input())

total = total + a

print 'The average is', total / 5

---------------------------------------------------

i = 0

total = 0

while i < 5:

print 'Please input number %d' % (i + 1)

a = float(raw_input())

i = i + 1

total = total + a

print 'The average is', total / 5

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

p = True

while p:

a = int(raw_input("please input a number between 1~100: "))

if a >= 1 and a <= 100:

print 'Very good!'

p = False

else:

print "Please try again!"

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

def sum():

total = 0

for i in range(0,5):

print "Please input number %d" % (i + 1)

a = int(raw_input())

total = total + a

print 'total = ',total

def average():

total = 0

for i in range(0,5):

print "Please input number %d" % (i + 1)

a = int(raw_input())

total = total + a

print 'average = ',total/5

print '''

Please input 1 to get the total of 5 numbers

Please input 2 to get the average of 5 numbers

Please input x to exit

'''

choice = raw_input()

if choice == '1':

sum()

elif choice == '2':

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__可以显示这个字符串的内容。许多内建函数、方法、模块及模块属性都有相应的文档字符串。我们希望你在你的代码中也要书写文档字符串,它会对使用这些代码的人提供及时方便的帮助。

答案:

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on

win32

Type "copyright", "credits" or "license()" for more information.

>>> dir()

['__builtins__', '__doc__', '__name__', '__package__']

>>> dir

>>> type(dir)

>>> 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 comprising (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 attributes\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解释器的方式。

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32

Type "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', '_getframe', '_mercurial',

'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright',

'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback',

'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',

'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion',

'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',

'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile',

'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info',

'warnoptions', 'winver']

>>> sys.version

'2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)]'

>>> sys.exit()

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

答案:

2-15.元素排序。

(a)让用户输入三个数值并分别将它们报存到3个不同的变量中。不使用列表或排序算法,自己写代码来对三个数由小到大排序。

(b)修改(a)的解决方案,使之从大到小排序。

答案:

(a)

a = int(raw_input("input number a: "))

b = int(raw_input("input number b: "))

c = int(raw_input("input number c: "))

if a > b:

a,b = b,a

if a > c:

a,c = c,a

if b > c:

b,c = c,b

print a,b,c

(b)

a = int(raw_input("input number a: "))

b = int(raw_input("input number b: "))

c = int(raw_input("input number c: "))

if a > b:

a,b = b,a

if a > c:

a,c = c,a

if b > c:

b,c = c,b

print c,b,a

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

答案:略

相关文档