python核心编程习题答案(第二章)

时间:2021-11-15 08:31:46

第一章的习题大家都懂得。。。。就不写了。。。

以下纯手打 纯自编  个别摘抄互联网  带注释  欢迎查阅。

2-2

(a)这段代码是用来计算1 + 2 * 4 等于什么的

(b)9

(c)不一样,什么也没有

(d)单独执行什么也没有  在解释其中会出现9

(e)按照你的想象力来吧

2-3

__author__ = 'longlong'
a = 3
b = 4
print 'a + b = %d' % (a + b)
print 'a - b = %d' % (a - b)
print 'a * b = %d' % (a * b)
print 'a / b = %d' % (a / b)
print 'b %% a = %d' % (b % a)
print 'a ^ b = %d' % (a ** b)

2-4

#(a)
__author__ = 'longlong'
str = raw_input('Please input your name:')
print 'Hello', str

#(b)
__author__ = 'longlong'
str = raw_input('Please input a number:')
print int(str)

2-5

#(a)
__author__ = 'longlong'
i = 0
while i <= 10:
print i
i += 1

#(b)
__author__ = 'longlong'
for i in range(0, 11):
print i

2-6

__author__ = 'longlong'
num = input('Please input your number:')
if num == 0:
print '=0'
elif num > 0:
print '>0'
else:
print '<0'

2-7

__author__ = 'longlong'
str = raw_input('Please input your str:')
for i in str:
print i
i = 0
while i < len(str):
print str[i]
i += 1

2-8

__author__ = 'longlong'
sum = 0
num = 0
list = []
for i in range(5):
num = input('your number:')
sum += num
list.append(num)
print sum
print list
2-9

__author__ = 'longlong'
sum = 0
num = 0
list = []
for i in range(5):
num = input('your number:')
sum += num
list.append(num)
sum = float(sum)
sum = sum / 5
print sum
print list


2-10

__author__ = 'longlong'
while True:
sum = raw_input('Please in put a number:')
sum = int(sum)
if sum == 16:
print 'OK'
break
else:
print 'No!!!'

2-11

__author__ = 'longlong'


def pingjun():
sum = 0
num = 0
list = []
for i in range(5):
num = input('your number:')
sum += num
list.append(num)
sum = float(sum)
sum = sum / 5
print sum
print list


def he():
sum = 0
num = 0
list = []
for i in range(5):
num = input('your number:')
sum += num
list.append(num)
print sum
print list

while True:
print 'input:\n' \
'(a)pingjun\n' \
'(b)he\n' \
'(x)quit\n'
choice = raw_input('input your choice:')
if choice.lower() == 'a':
pingjun()
elif choice.lower() == 'b':
he()
elif choice.lower() == 'x':
break
else:
print 'Please input your choice again!!!!'

2-12

(a)

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
(b)

可以看到放进去东西里面都有什么,比如放进去头文件可以看见都文件里面的函数。

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

注释:这就是dir里面的doc,写着dir的用处等信息

2-13

(a)

>>> dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__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.__doc__
"This module provides access to some objects used or maintained by the\ninterpreter and to functions that interact strongly with the interpreter.\n\nDynamic objects:\n\nargv -- command line arguments; argv[0] is the script pathname if known\npath -- module search path; path[0] is the script directory, else ''\nmodules -- dictionary of loaded modules\n\ndisplayhook -- called to show results in an interactive session\nexcepthook -- called to handle any uncaught exception other than SystemExit\n  To customize printing in an interactive session or to install a custom\n  top-level exception handler, assign other functions to replace these.\n\nexitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n  Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\nstdin -- standard input file object; used by raw_input() and input()\nstdout -- standard output file object; used by the print statement\nstderr -- standard error object; used for error messages\n  By assigning other file objects (or objects that behave like files)\n  to these, it is possible to redirect all of the interpreter's I/O.\n\nlast_type -- type of last uncaught exception\nlast_value -- value of last uncaught exception\nlast_traceback -- traceback of last uncaught exception\n  These three are only available in an interactive session after a\n  traceback has been printed.\n\nexc_type -- type of exception currently being handled\nexc_value -- value of exception currently being handled\nexc_traceback -- traceback of exception currently being handled\n  The function exc_info() should be used instead of these three,\n  because it is thread-safe.\n\nStatic objects:\n\nfloat_info -- a dict with information about the float inplementation.\nlong_info -- a struct sequence with information about the long implementation.\nmaxint -- the largest supported integer (the smallest is -maxint-1)\nmaxsize -- the largest supported length of containers.\nmaxunicode -- the largest supported character\nbuiltin_module_names -- tuple of module names built into this interpreter\nversion -- the version of this interpreter as a string\nversion_info -- version information as a named tuple\nhexversion -- version information encoded as a single integer\ncopyright -- copyright notice pertaining to this interpreter\nplatform -- platform identifier\nexecutable -- absolute path of the executable binary of the Python interpreter\nprefix -- prefix used to find the Python library\nexec_prefix -- prefix used to find the machine-specific Python library\nfloat_repr_style -- string indicating the style of repr() output for floats\n__stdin__ -- the original stdin; don't touch!\n__stdout__ -- the original stdout; don't touch!\n__stderr__ -- the original stderr; don't touch!\n__displayhook__ -- the original displayhook; don't touch!\n__excepthook__ -- the original excepthook; don't touch!\n\nFunctions:\n\ndisplayhook() -- print an object to the screen, and save it in __builtin__._\nexcepthook() -- print an exception and its traceback to sys.stderr\nexc_info() -- return thread-safe information about the current exception\nexc_clear() -- clear the exception state for the current thread\nexit() -- exit the interpreter by raising SystemExit\ngetdlopenflags() -- returns flags to be used for dlopen() calls\ngetprofile() -- get the global profiling function\ngetrefcount() -- return the reference count for an object (plus one :-)\ngetrecursionlimit() -- return the max recursion depth for the interpreter\ngetsizeof() -- return the size of an object in bytes\ngettrace() -- get the global debug tracing function\nsetcheckinterval() -- control how often the interpreter checks for events\nsetdlopenflags() -- set the flags to be used for dlopen() calls\nsetprofile() -- set the global profiling function\nsetrecursionlimit() -- set the max recursion depth for the interpreter\nsettrace() -- set the global debug tracing function\n"

(d)

非常简单不写了。。。