python核心编程第二版 第二章练习题解答 未完待续

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python核心编程第二版 第二章练习题解答 未完待续相关的知识,希望对你有一定的参考价值。

有人可能会想,连2-1和2-2这样的题目都回答,够无聊的啊。
因为现在处于并长期处于成为大师的第一阶段------守的阶段



2-1

>>> a= ‘123‘
>>> a
‘123‘
>>> print (a)
123

a是字符串123,如果格式化输出有问题报如下错误:

>>> print (‘a is %d‘% a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

这样就正确了。

>>> print (‘a is %s‘ % a)
a is 123

a如果是×××:

>>> a = 123
>>> print (‘a is %s‘% a)
a is 123
>>> a
123
>>> print (a)
123
>>> print (‘a is %d‘ %a )
a is 123

print和交互式解释器显示对象的区别:
print调用str()函数显示对象,而交互式解释器则调用repr()函数来显示对象。



2-2

(a) 用来计算1+2x4的结果
(b)作为脚本什么都不输出
(c)预期的一样,因为这个脚本没有print输出
(d)在交互式系统中有输出,如下:

>>> #!/usr/bin/env python
... 1 + 2 * 4
9
>>>

(e)脚本改进如下:

#!/usr/bin/env python
print (1 + 2 * 4)

输出结果如下:

技术图片



2-3

在python3中/是真正的除法,//是地板除(取整,取比实际除法得到的结果小最近的整数)

技术图片

技术图片



2-4

脚本:

[[email protected]_01 P36practise]# cat 2_4.py
#!/usr/bin/env python
x =  raw_input("please input a string:
")
print x

运行结果:

[[email protected]_01 P36practise]# python 2_4.py
please input a string:
ad cd
ad cd


2-5

[[email protected]_01 P36practise]#  cat 2-5.py
#!/usr/bin/env python
print 
print ("using loop while:")

i = 0
while i < 11 :
    print i
    i += 1
print 

print ("*"*50)

print ("using loop for:")

for i in range(11):
    print i
print 

运行结果:

[[email protected]_01 P36practise]# python 2-5.py 

using loop while:
0
1
2
3
4
5
6
7
8
9
10

**************************************************
using loop for:
0
1
2
3
4
5
6
7
8
9
10


2-6

[[email protected]_01 P36practise]# cat 2-6.py 
#!/usr/bin/env python
import sys

print ("if you want to exit the program please insert q
")
i = raw_input("please input a number:
")

def fun(i):    
    try:
        i = int(i)
    except ValueError:
        print ("WARNING !!! %s is not permit 
please input a num or ‘q‘:
")%i
        sys.exit()
    if i < 0:
        print "judge:%d is negative" % i
        print 

    elif i == 0:
        print "judge:%d is zero" % i
        print

    else:
        print "judge:%d is positive" % i
        print

while i != ‘q‘:
    fun(i)
    i = raw_input("please input a number:
")

else:
    sys.exit()

运行结果:(输入ctrl+c退出)

[[email protected]_01 P36practise]# python 2-6.py 
if you want to exit the program please insert q

please input a number:
1
judge:1 is positive

please input a number:
-1
judge:-1 is negative

please input a number:
0
judge:0 is zero

please input a number:
^CTraceback (most recent call last):
  File "2-6.py", line 27, in <module>
    i = raw_input("please input a number:
")
KeyboardInterrupt

输入q退出:

[[email protected]_01 P36practise]# python 2-6.py
if you want to exit the program please insert q

please input a number:
-1
judge:-1 is negative

please input a number:
1   
judge:1 is positive

please input a number:
q
[[email protected]_01 P36practise]# 


2-7

[[email protected]_01 P36practise]# cat 2-7.py
#!/usr/bin/env python
#encoding:utf8

import sys

str = raw_input("please input a string:
")
for i in str:
    print i

print "*"*50
print

print "网上搜来的方法:
"
i = 0
while i < len(str):
    print str[i]
    i += 1

print "野路子
"

i = 0
while str:
    try:
        print str[i]
    except IndexError:
        sys.exit()
    i += 1

[[email protected]_01 P36practise]# 

运行结果:

[[email protected]_01 P36practise]# python 2-7.py 
please input a string:
ahead blonging ok
a
h
e
a
d

b
l
o
n
g
i
n
g

o
k
**************************************************

网上搜来的方法:

a
h
e
a
d

b
l
o
n
g
i
n
g

o
k
野路子

a
h
e
a
d

b
l
o
n
g
i
n
g

o
k

修改程序后,禁止掉他的换行

[[email protected]_01 P36practise]# cat 2-7.py
#!/usr/bin/env python
#encoding:utf8

import sys

str = raw_input("please input a string:
")
print 
for i in str:
    print i,
print 
print 
print "*"*50
print

print "网上搜来的方法:
"
i = 0
while i < len(str):
    if i == len(str):
        print str[i]
    else:
        print str[i],
    i += 1
print 
print 
print "野路子:
"

i = 0
while str:
    try:
        print str[i],
    except IndexError:
        sys.exit()
    i += 1

[[email protected]_01 P36practise]#

运行结果:

[[email protected]_01 P36practise]# python 2-7.py
please input a string:
what

w h a t

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

网上搜来的方法:

w h a t

野路子:

w h a t
[[email protected]_01 P36practise]# 


2-8

[[email protected]_01 P36practise]# cat 2-8.py
#!/usr/bin/env python

#tuple1 = (1, 2, 3, 4, 5)
#list1 = [5, 6, 7, 8, 9]
#
def sum1(x):
    sum = 0
    for i in x:
        sum += i
    print sum,"sum1"

def sum2(x):
    sum = 0
    i = 0
    list2 = list(x)
    while i < len(list2):
        sum += list2[i]
        i += 1
    print sum,‘sum2‘

#print "using for sum
"
#sum1(tuple1)
#sum1(list1)
#print

#print "using while sum
"
#sum2(list1)
#sum2(tuple1)
#
#print 
#print "interactive input tuple or list:
"
#
x = raw_input("please input a tuple or list:
")
def f(x):
    l = []
    for i in x.split(‘ ‘):
        try:
            l.append(int(i))
        except ValueError:
            print ‘the value you input have some innumberal character
‘
    return l 
y = f(x)
sum1(y)

运行结果

[[email protected]_01 P36practise]# python 2-8.py
please input a tuple or list:
1 2 3 4 5
15 sum1


2-9

[[email protected]_01 P36practise]# cat 2-9.py
#!/usr/bin/env python

#tuple1 = (1, 2, 3, 4, 5)
#list1 = [5, 6, 7, 8, 9]
#
def sum1(x):
    sum = 0
    for i in x:
        sum += i
    return sum

def sum2(x):
    sum = 0
    i = 0
    list2 = list(x)
    while i < len(list2):
        sum += list2[i]
        i += 1
    return sum,list2

def average(x,y):
    z = float(x) / y 
    print z
#print "using for sum
"
#sum1(tuple1)
#sum1(list1)
#print

#print "using while sum
"
#sum2(list1)
#sum2(tuple1)
#
#print 
#print "interactive input tuple or list:
"
#
x = raw_input("please input a tuple or list:
")
def f(x):
    l = []
    for i in x.split(‘ ‘):
        try:
            l.append(int(i))
        except ValueError:
            print ‘the value you input have some innumberal character
‘
    return l 
y = f(x)
average(sum1(y),len(y))

运行结果:

[[email protected]_01 P36practise]# python 2-9.py
please input a tuple or list:
1 2 3 4 5
3.0


2-10

代码:

[[email protected]_01 P36practise]# cat 2-10.py
#!/usr/bin/env python
#encoding:utf
import sys

def num_judge(x):
    if x >= 1 and x <= 100:
        return True
    else:
        return False
while 1:
    try:
        x = int(raw_input(‘please input a num:
‘))
    except ValueError:
        print "please input a number! byebye!
"
        sys.exit()
   #一开始没有对x进行int处理,导致在1~100之间的数字也不能成功
    print ‘*‘*50
    if num_judge(x):
        print "success!"
        print 

    else:
        print ‘please input a number between 1 and 100‘
    print 
           # else:
   #     x = raw_input(‘please input a num:
‘)
   # 一开始有这个部分,导致下面这种情况出错:
   # 先输入一个不符合的数字,然后再输入一个符合的,这是这个第一次符合的数字会误判成不符合,就是因为多写了这个else
   # 后来把else:里面加了pass。后来发现干脆把else去掉了。i‘‘‘

#while 循环的核心思想是,只要为真,while中的子句总是从上往下一直执行下去

运行结果:

[[email protected]_01 P36practise]# python 2-10.py
please input a num:
1
**************************************************
success!

please input a num:
2
**************************************************
success!

please input a num:
101
**************************************************
please input a number between 1 and 100

please input a num:
adf
please input a number! byebye!

[[email protected]_01 P36practise]# 


2-11

[[email protected]_01 P36practise]# cat 2-11.py
#!/usr/bin/env python
#encoding:utf8

import sys

#求和
def sum1(x):
    sum = 0
    for i in x:
        sum += i
    return sum

#求平均值
def average(x,y):
    z = float(x) / y 
    print z
#转换输入的数据
def f(x):
    l = []
    for i in x.split(‘ ‘):
        try:
            l.append(int(i))
        except ValueError:
            print ‘the value you input have some innumberal character
‘
    return l 

def max(x):
    print "The maxium num in this line is :
"

x = raw_input("please input a tuple or list:
")
y = f(x)

print "please choose you calculator:
"

print "(1)取五个数的和:
(2)取五个数的平均值
(X)退出
"

while 1:
    k = raw_input("please input a str in 1,2, ..., X:
")

    if k == ‘1‘:
        print sum1(y)
    if k == ‘2‘:
        sum1(y)
        print "*"*50
        average(sum1(y),len(y))
    if k == ‘3‘:
        max(y)
    if k == ‘X‘:
        sys.exit()

运行结果:

[[email protected]_01 P36practise]# python 2-11.py
please input a tuple or list:
a 2 3 4 5
the value you input have some innumberal character

please choose you calculator:

(1)取五个数的和:
(2)取五个数的平均值
(X)退出

please input a str in 1,2, ..., X:
1
14
please input a str in 1,2, ..., X:
2
**************************************************
3.5
please input a str in 1,2, ..., X:
x
please input a str in 1,2, ..., X:
X
[[email protected]_01 P36practise]# 


2-12

dir([obj]) 显示对象的属性,如果没有提供参数,则显示全局变量的名字。

(a)

>>> dir()
[‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘]

>>> 
>>> dir(__builtins__)
[‘ArithmeticError‘, ‘AssertionError‘, ‘AttributeError‘, ‘BaseException‘, ‘BufferError‘, ‘BytesWarning‘, ‘DeprecationWarning‘, ‘EOFError‘, ‘Ellipsis‘, ‘EnvironmentError‘, ‘Exception‘, ‘False‘, ‘FloatingPointError‘, ‘FutureWarning‘, ‘GeneratorExit‘, ‘IOError‘, ‘ImportError‘, ‘ImportWarning‘, ‘IndentationError‘, ‘IndexError‘, ‘KeyError‘, ‘KeyboardInterrupt‘, ‘LookupError‘, ‘MemoryError‘, ‘NameError‘, ‘None‘, ‘NotImplemented‘, ‘NotImplementedError‘, ‘OSError‘, ‘OverflowError‘, ‘PendingDeprecationWarning‘, ‘ReferenceError‘, ‘RuntimeError‘, ‘RuntimeWarning‘, ‘StandardError‘, ‘StopIteration‘, ‘SyntaxError‘, ‘SyntaxWarning‘, ‘SystemError‘, ‘SystemExit‘, ‘TabError‘, ‘True‘, ‘TypeError‘, ‘UnboundLocalError‘, ‘UnicodeDecodeError‘, ‘UnicodeEncodeError‘, ‘UnicodeError‘, ‘UnicodeTranslateError‘, ‘UnicodeWarning‘, ‘UserWarning‘, ‘ValueError‘, ‘Warning‘, ‘ZeroDivisionError‘, ‘_‘, ‘__debug__‘, ‘__doc__‘, ‘__import__‘, ‘__name__‘, ‘__package__‘, ‘abs‘, ‘all‘, ‘any‘, ‘apply‘, ‘basestring‘, ‘bin‘, ‘bool‘, ‘buffer‘, ‘bytearray‘, ‘bytes‘, ‘callable‘, ‘chr‘, ‘classmethod‘, ‘cmp‘, ‘coerce‘, ‘compile‘, ‘complex‘, ‘copyright‘, ‘credits‘, ‘delattr‘, ‘dict‘, ‘dir‘, ‘divmod‘, ‘enumerate‘, ‘eval‘, ‘execfile‘, ‘exit‘, ‘file‘, ‘filter‘, ‘float‘, ‘format‘, ‘frozenset‘, ‘getattr‘, ‘globals‘, ‘hasattr‘, ‘hash‘, ‘help‘, ‘hex‘, ‘id‘, ‘input‘, ‘int‘, ‘intern‘, ‘isinstance‘, ‘issubclass‘, ‘iter‘, ‘len‘, ‘license‘, ‘list‘, ‘locals‘, ‘long‘, ‘map‘, ‘max‘, ‘memoryview‘, ‘min‘, ‘next‘, ‘object‘, ‘oct‘, ‘open‘, ‘ord‘, ‘pow‘, ‘print‘, ‘property‘, ‘quit‘, ‘range‘, ‘raw_input‘, ‘reduce‘, ‘reload‘, ‘repr‘, ‘reversed‘, ‘round‘, ‘set‘, ‘setattr‘, ‘slice‘, ‘sorted‘, ‘staticmethod‘, ‘str‘, ‘sum‘, ‘super‘, ‘tuple‘, ‘type‘, ‘unichr‘, ‘unicode‘, ‘vars‘, ‘xrange‘, ‘zip‘]

>>>
>>> dir(__doc__)
[‘__class__‘, ‘__delattr__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘]
>>> dir(__name__)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘_formatter_field_name_split‘, ‘_formatter_parser‘, ‘capitalize‘, ‘center‘, ‘count‘, ‘decode‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdigit‘, ‘islower‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
>>> 
>>> 
>>> 
>>> dir(__package__)
[‘__class__‘, ‘__delattr__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘]

(b)

>>> dir
<built-in function dir>
表示dir是内建函数

(c)

>>> type(dir)
<type ‘builtin_function_or_method‘>

(d)

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

(a)

[[email protected]_01 P36practise]# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
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‘, ‘_debugmallocstats‘, ‘_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‘, ‘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.5 (default, Aug  4 2017, 00:39:18) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]‘
>>> sys.platform
‘linux2‘
>>>        

(c)


>>> 
>>> sys.exit()
[[email protected]_01 P36practise]# 


2-14

操作符优先级:+和-优先级最低,、*、/、//、%优先级较高,单目操作符+和-优先级更高(正负号),乘方的优先级最高。

>>> print -2*4 + 3**2
1
>>> print (-2*4) + (3**2)
1
>>> print (-2)*4 + (3**2)
1

以上是关于python核心编程第二版 第二章练习题解答 未完待续的主要内容,如果未能解决你的问题,请参考以下文章

Python核心编程第二版 第六章课后练习

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

Python核心编程(第二版)第六章部分习题代码

《python核心编程第二版》课后习题6-12答案

Python核心编程(第二版)正则表达式练习题解

python核心编程第二版