- 写出下列命令的结果
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
2.写出下列命令的结果
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
3.写出下列命令的结果
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
>>> e.kind # shared by all dogs
>>> d.name # unique to d
>>> e.name # unique to e
4.写出下列命令的结果
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks # unexpectedly
5.写出下列命令的结果
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
6.写出下列命令的结果
>>> s = 'abc'
>>> it = iter(s)
>>> it
>>> next(it)
>>> next(it)
>>> next(it)
>>> next(it)
7.写出下列命令的结果
>>> rev = Reverse('spam')
>>> iter(rev)
>>> for char in rev:
... print(char)
...
8.写出下列命令的结果
>>> for char in reverse('golf'):
... print(char)
9.写出下列命令的结果
>>> sum(i*i for i in range(10)) # sum of squares
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
>>> from math import pi, sin
>>> sine_table = {x: sin(x*pi/180) for x in range(0, 91)}
>>> unique_words = set(word for line in page for word in line.split())
>>> valedictorian = max((student.gpa, student.name) for student in graduates)
>>> data = 'golf'
>>> list(data[i] for i in range(len(data)-1, -1, -1))
10.写出下列命令的结果
>>> import os
>>> os.getcwd() # Return the current working directory
>>> os.chdir('/server/accesslogs') # Change current working directory
>>> os.system('mkdir today') # Run the command mkdir in the system shell
11.写出下列命令的结果
>>> import os
>>> dir(os)
>>> help(os)
12.写出下列命令的结果
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
13.写出下列命令的结果
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')
14.写出下列命令的结果
>>> import glob
>>> glob.glob('*.py')
15.写出下列命令的结果
>>> import sys
>>> print(sys.argv)
16.写出下列命令的结果
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
17.写出下列命令的结果
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
18.写出下列命令的结果
>>> 'tea for too'.replace('too', 'two')
19.写出下列命令的结果
>>> import math
>>> math.cos(math.pi / 4)
>>> math.log(1024, 2)
20.写出下列命令的结果
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10) # sampling without replacement
>
>>> random.random() # random float
>>> random.randrange(6) # random integer chosen from range(6)
21.写出下列命令的结果
>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
>>> statistics.median(data)
>>> statistics.variance(data)
22.写出下列命令的结果
>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
23.写出下列命令的结果
>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
>>> t = zlib.compress(s)
>>> len(t)
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
24.写出下列命令的结果
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
25.写出下列命令的结果
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
26.写出下列命令的结果
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
27.写出下列命令的结果
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
28.写出下列命令的结果
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
>>> conv = locale.localeconv() # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
30.写出下列命令的结果
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
31.写出下列命令的结果
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
32.写出下列命令的结果
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
33.写出下列命令的结果
>>> import weakref, gc
>>> class A:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return str(self.value)
...
>>> a = A(10) # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a # does not create a reference
>>> d['primary'] # fetch the object if it is still alive
>>> del a # remove the one reference
>>> gc.collect() # run garbage collection right away
>>> d['primary'] # entry was automatically
34.写出下列命令的结果
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
>>> a[1:3]
35.写出下列命令的结果
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
36.写出下列命令的结果
>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
37.写出下列命令的结果
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data) # rearrange the list into heap order
>>> heappush(data, -5) # add a new entry
>>> [heappop(data) for i in range(3)]
38.写出下列命令的结果
>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)