*** Strona 223-224 ***************************************************************

>>> dir([])                            # jakie s atrybuty list?
['append', 'count', 'index', 'insert', 'remove', 'reserve', 'sort']

>>> dir(())                            # jakie s atrybuty krotek?
[]                                     # krotki nie maj atrybutw!

>>> dir(sys.stdin)                     # jakie s atrybuty plikw?
['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read',  
 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 
 'write', 'writelines']
 >>> dir(sys)                          # moduy s take obiektami
 ['__doc__', '__name__', 'argv', 'builtin_module_names', 'copyright', 
 'dllhandle', 'exc_info', 'exc_type', 'exc_prefix', 'executable', 'exit', 
 'getrefcount', 'maxint', 'modules', 'path', 'platform', 'prefix', 'ps1', 
 'ps2', 'setcheckinterval', 'setprofile', 'settrace', 'stderr', 'stdin', 
 'stdout', 'version', 'winver']

>>> type(sys.version)                  # jakiego typu jest 'version'?
<type 'string'>

>>> print sys.version                  # jaka jest warto tego acucha?
1.5 (#0, Dec 30 1997, 23:24:20) [MSC 32 bit (Intel)]


*** Strona 225 *******************************************************************

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'EOFError', 
 'Ellipsis', 'Exception', 'FloatingPointError', 'IOError', 'ImportError', 
 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 
 'NameError', 'None', 'OverflowError', 'RuntimeError', 'StandardError', 
 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', 
 'ZeroDivisionError, '__debug__', '__doc__', '__import__', '__name__', 'abs', 
 'apply', 'callable', 'chr', 'cmp', 'coerce', 'compile', 'complex', 'delattr', 
 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float', 'getattr', 'globals', 
 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 
 'issubclass', 'len', 'list', 'locals', 'long', 'map', 'max', 'min', 'oct', 
 'open', 'ord', 'pow', 'range', 'raw_input', 'reduce', 'reload', 'repr', 
 'round', 'setattr', 'slice', 'str', 'tuple', 'type', 'vars', 'xrange']


*** Strona 226-227 ***************************************************************

>>> int(1.0), int(1.4), int(1.9), round(1.9), int(round(1.9))
(1, 1, 1, 2.0, 2)

>>> int("1")
1

>>> int("1.2")                                      # to nie dziaa
Traceback (innermost last):
  File "<stdin>", line 1, in?
ValueError: invalid literal for int(): 1.2

>>> int("1.0")                                      # ani to nie dziaa
Traceback (innermost last):         # poniewa 1.0 take nie jest poprawne
  File "<stdin>", line 1, in ?      # literalny zapis liczby cakowitej
ValueError: invalid literal for int(): 1.0

>>> hex(1000), oct(10000), complex(1000), long(1000)
('0x3e8', '023420', (1000+0j), 1000L)

>>> def safeint(candidate):
...     import math
...     truncated = math.floor(float(candidate))
...     rounded = round(float(candidate))
...     if truncated == rounded:
...         return int(truncated)
...     else:
...         raise ValueError, "utrata precyzji po zamianie na integer"
...
>>> safeint(3.0)
3
>>> safeint("3.0")
3
>>> safeint(3.6)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in safein
ValueError: utrata precyzji po zamianie na integer

>>> abs(-1), abs(-1.2), abs(-3+4j)
(1, 1.2, 5.0)    # 5 jest sqrt(3*3 + 4*4)

>>> map(ord, "test")       # naley pamita, e acuchy s sekwencjami
[116, 101, 115, 116]       # znakw, zatem mona uy map
>>> chr(64)
'@'
>>> ord('@')
64

# map zwraca list pojedynczych znakw, a wic
# musi by doczone ('join') do acucha

>>> map(chr, (77, 105, 101, 108, 111, 110, 107, 97, 33))
['M', 'i', 'e', 'l', 'o', 'n', 'k', 'a', '!']
>>> import string
>>> string.join(map(chr, (77, 105, 101, 108, 111, 110, 107, 97, 33)), '')
'Mielonka!'

>>> min("pif", "paf", "pof")       # gdy wywoana za pomoc wielokrotnoci
'paf'                              # zwraca jeden waciwy
>>> min("ZELDA!"), max("ZELDA!")   # gdy wywoana za pomoc sekwencji,
('!', 'Z')                         # zwraca jej element min/max


*** Strona 227-228 ***************************************************************

>>> str(dir())
"['__builtins__', '__doc__', '__name__']"

>>> list("pomidor")
['p', 'o', 'm', 'i', 'd', 'o', 'r']
>>> list((1,2,3))
[1, 2, 3]

>>> tuple("pomidor")
('p', 'o', 'm', 'i', 'd', 'o', 'r')
>>> tuple([0])
(0,)

>>> int("3")
3

>>> long("3")
3L

>>> float("3")
3.0

>>> complex(3,5)
(3+5j)

>>> hex(10000)
'0x2710'

>>> oct(10000)
'023420'

>>> ord('A')
65

>>> chr(65)
'A'

>>> min([5,1,2,3,4])
1
>>> min(5,1,2,3,4)
1

>>> max([5,1,2,3,4])
5
>>> max(5,1,2,3,4)
5


*** Strona 229 *******************************************************************

>>> def increment_attribute(Object, attrname):
...     if not hasattr(Object, attrname):
...         setattr(Object, attrname, 1)
...     else:
...         setattr(Object, attrname, getattr(Object, attrname) + 1)
...
>>> class Test: pass
...
>>> aname = 'foo'
>>> increment_attribute(Test, aname)   # tworzy Test.foo i ustawia go na 1
>>> increment_attribute(Test, aname)   # powiksza Test.foo
>>> Test.foo
2

def increment_attribute(Object, attrname):
    setattr(Object, attrname, getattr(Object, attrname, 0) + 1)


*** Strona 230-232 ***************************************************************

>>> code = "x = 'Cos'"
>>> x = "Nic"             # ustawia warto x
>>> exec code             # modyfikuje warto!
>>> print x
Cos

import sys
for argument in sys.argv[1:]:  # przeskoczymy samych siebie lub zaptlimy!
    execfile(argument)         # robi cokolwiek

>>> z = eval("'xo'*10")
>>> print z
xoxoxoxoxoxoxoxoxoxo

>>> z = eval("x = 3")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1
    x = 3
      ^
SyntaxError: invalid syntax

>>> callable(sys.exit), type(sys.exit)
(1, <type 'builtin_function_or_method'>)
>>> callable(sys.version), type(sys.version)
(0, <type 'string'>)


*** Strona 233-234 ***************************************************************

>>> string.atof("1.4")
1.4

>>> string.atoi("365")
365

>>> string.atol("987654321")
987654321L

>>> string.capitalize("pomidor")
'Pomidor'

>>> string.capwords("teraz jest czas")
'Teraz Jest Czas'

>>> string.find("teraz jest czas", 'jest')
6

>>> string.count("teraz jest czas", 'a')
2

>>> string.replace("teraz jest  czas", ' ', '_')
'teraz_jest_czas'

>>> string.split("teraz jest czas")
['teraz', 'jest', 'czas']

>>> string.join(["teraz", "jest", "czas"], '*')
'teraz*jest*czas'
>>> string.join("teraz jest czas", '*')
't*e*r*a*z* *j*e*s*t* *c*z*a*s'

>>> string.strip(" przed i po ")
'przed i po'


*** Strona 236-238 ***************************************************************

# plik pepper.txt

This is a paragraph that mentions bell peppers multiple times. For one, here 
is a red pepper and dried tomato salad recipe. I don't like to use green 
peppers in my salads as much because they have a harsher flavor.

This second paragraph mentions red peppers and green peppers but not the "s" 
word (s-a-l-a-d), so no bells should show up.

This third paragraph mentions red peppercorns and green peppercorns, which 
aren't vegetables but spices (by the way, bell peppers really aren't peppers, 
they're chilies, but would you rather have a good cook or a good botanist 
prepare your salad?).


# plik pepper.py

file = open('pepper.txt')
text = file.read()

import string
paragraphs = string.split(text, '\n\n')

import re
matchstr = re.compile(
    r"""\b(red|green)       # 'red' lub 'green' rozpoczyna nowe sowa,
          (\s+              # za ktrymi nastpuje spacja,
          pepper            # potem sowo 'pepper'
          (?!corn)          # jeli nie poprzedzone sowem 'corn'
          (?=.*salad))""",  # i jeli gdzie wystpuje "salad"
       re.IGNORECASE |      # zezwalamy na pepper, Pepper, PEPPER, itd.
       re.DOTALL |          # oraz na dopasowanie znakw nowego wiersza 
       re.VERBOSE)          # pozwala to na komentarze i znaki nowego wiersza
for paragraph in paragraphs:
    fixed_paragraph = matchstr.sub(r'bell\2', paragraph)
    print fixed_paragraph+'\n'


/home/David/book$ python pepper.py
This is a paragraph that mentions bell peppers multiple times. For one, here 
is a bell pepper and dried tomato salad recipe. I don't like to use bell 
peppers in my salads as much because they have a harsher flavor.

This second paragraph mentions red peppers and green peppers but not the "s" 
word (s-a-l-a-d), so no bells should show up.

This third paragraph mentions red peppercorns and green peppercorns, which 
aren't vegetables but spices (by the way, bell peppers really aren't peppers, 
they're chilies, but would you rather have a good cook or a good botanist 
prepare your salad?).


*** Strona 239 *******************************************************************

>>> print os.getcwd()
h:\David\book

>>> os.listdir(os.getcwd())
['preface.doc', 'part1.doc', 'part2.doc']


>>> os.rmdir('nieistniejacy_katalog')     # tak to si zwykle pokazuje
Traceback (innermost last):
  File "<stdin>", line 1, in ?
os.error: (2, 'No such file or directory')
>>> try:                                  # moemy wyapa bd i odrzuci
...    os.rmdir('nieistniejacy_katalog')  # go dalej
... except os.error, value:
...    print value[0], value[1]
...
2 No such file or directory


>>> print os.environ['SHELL']
/bin/sh
>>> os.environ['STARTDIR'] = 'MyStartDir'
>>> os.system('echo $STARTDIR')     # 'echo %STARTDIR%' dla DOS/Win
MyStartDir                          # drukowane przez powok 
0                                   # zwraca kod z echa


*** Strona 241 *******************************************************************

>>> os.path.split("h:/David/book/part2.doc")
('h:/David/book', 'part2.doc')

>>> print os.path.join(os.getcwd(),
... os.pardir, 'backup', 'part2.doc')
h:\David\book\..\backup\part2.doc

>>> print os.path.expanduser('~/mydir')
h:\David\mydir 

>>> print os.path.expandvars('$TMP')
c:\TEMP

>>> print os.path.normpath("/foo/bar\\../tmp")
\foo\tmp

>>> def test_walk(arg, dirname, names):
...     print arg, dirname, names
...
>>> os.path.walk('..', test_walk, 'show')
show ..\logs ['errors.log', 'access.log']
show ..\cgi-bin ['test.cgi']
...


*** Strona 243-244 ***************************************************************

>>> page = urllib.urlopen('http://www.python.org')
>>> page.readline()
'<HTML>\012'
>>> page.readline()
'<!-- THIS PAGE IS AUTOMATICALLY GENERATED. DO NOT EDIT. -->\012'

>>> urllib.urlretrieve('http://www.python.org/', 'wwwpython.html')

>>> urllib.quote('this & that @ home')
'this%20%26%20that%20%40%20home'

>>> urllib.unquote('this%20%26%20that%20%40%20home')
'this & that @ home'

>>> locals()
{'urllib': <module 'urllib'>, '__doc__': None, 'x':
3, '__name__': '__main__', '__buitins__': <module  '__builtin__'>}
>>> urllib.urlencode(locals())
'urllib=%3cmodule+%27urllib%27%3e&__doc__=None&x=3&
__name__=__main__&+__builtins__=%3cmodule+%27
__builtin__%27%3e'

>>> urlparse.urlparse('http://www.python.org/FAQ.html')
('http', 'www.python.org', '/FAQ.html', '', '',  '')

>>> urlparse.urljoin('http://www.python.org', 'doc/lib')
'http://www.python.org/doc/lib'


*** Strona 246 *******************************************************************

import struct

data = open('bindat.dat').read()
start, stop = 0, struct.calcsize('fl')
version_number, num_bytes = struct.unpack('fl', data[start:stop])
start, stop = stop, start + struct.calcsize('B'*num_bytes)
bytes = struct.unpack('B'*num_bytes, data[start:stop])


*** Strona 247 *******************************************************************

>>> import mielonka     # importuje modu, w ktrym chcemy wyszukiwa bdy
>>> import pdb                                 # importujemy pdb
>>> pdb.run('instance = mielonka.Mielonka()')  # uruchamiamy pdb
> <string>(0)?()
(Pdb) break mielonka.Mielonka.__init__         # moemy ustali puapki
(Pdb) next
> <string>(1)?()
(Pdb) n                                # 'n' jest skrtem od 'next' (nastpny)
> mielonka.py(3)__init__()
-> def __init__(self):
(Pdb) n
> mielonka.py(4)__init__()
-> Mielonka.numInstances = Mielonka.numInstances + 1
(Pdb) list                             # pokazuje wydruk kodu rdowego
  1    class Mielonka:     
  2        numInstances = 0
  3 B      def __init__(self):         # zwrmy uwag na B jako Breakpoint
  4   ->       Mielonka.numInstances = Mielonka.numInstances + 1  # tutaj 
                jestemy
  5        def printNumInstances(self):
  6            print "Liczba utworzonych egzemplarzy: ", Mielonka.numInstances
  7
[EOF]
(Pdb) where                            # pokazuje stos wywoujcego 
  <string>(1)?()
> mielonka.py(4)__init__()
-> Mielonka.numInstances = Mielonka.numInstances + 1
(Pdb) Mielonka.numInstances = 10       # moemy zmodyfikowa zmienn
(Pdb) print Mielonka.numInstances      # gdy trwa wyszukiwanie bdw
10
(Pdb) continue                         # kontynuacja do nastpnej puapki,
--Return--                             # ktrej nie ma, zatem
> <string>(1)?()->None                 # wszystko gotowe
(Pdb) c                                # to koczy Pdb
<mielonka.Mielonka instance at 80ee60> # to jest przykadowy wynik
>>> instance.numInstance               # uwaga na zmian numInstances
11                                     # to byo *przed* zwikszeniem op


*** Strona 248 *******************************************************************

# plik makezeros.py

def lots_of_appends():
    zera = []
    for i in range(10000):
        zera.append(0)

def one_multiply():
    zera = [0] * 10000

# plik timings.py

import time, makezeros

def do_timing(num_times, funcs):
    totals = {}
    for func in funcs: totals[func] = 0.0
    for x in range(num_times):
        for func in funcs:
            starttime = time.time()       # czas rozpoczcia 
            apply(func)
            stoptime = time.time()        # czas zakoczenia
            elapsed = stoptime-starttime  # rnica (czas skonsumowany)
            totals[func] = totals[func] + elapsed
    for func in funcs:
        print "Running %s %d times took %.3f seconds" % (func.__name__, num_times, totals[func])

do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply))


csh> python timings.py
Running lots_of_appends 100 times took 7.891 seconds
Running one_multiply 100 times took 0.120 seconds


>>> import profile
>>> from timings import *
>>> from makezeros import *
>>> profile.run('do_timing(100, (lots_of_appends, one_multiply))')
Running lots_of_appends 100 times took 8.773 seconds
Running one_multiply 100 times took 0.090 seconds
...


***kod do wicze znajduje si w katalogu "rozwiazania"***