Está en la página 1de 152

1.

1
1.2
1.3
1.4
Python 1.5
1.6
1.7
1.8
1.9
1.10
1.11
1.12
1.13
1.14
1.15
1.16
1.17
1.18
1.19
1.20
FLOSS 1.21
1.22
1.23
1.24
1.25
1.26

Python
A Byte of Python Swaroop C H Python
Python

2005 1.20
Python 2017 4.0

4.04c 2017 5 1

Python 3
Python 3
Python 2

Walt Michalik

Python
-- Joshua Robin

#Python -- Shan Rajasekaran

Python -- Nickson Kaigi

Python -- Herbert Feutl

Python Python -- Dilip

Python
-- Biologist John

Python
Pythonistas Python -- Mangesh

Python Swaroop
-- Apostolos

@swaroopch #ByteOfPython -- Yuvraj Sharma

Python

-- Franklin

Dayanandasagar CSE
Python Python
Python -- Madhura

18
Python 3
CJava Javascript Python
Python

-- Matt

Pavel Python
:)
-- Pavel Simo

Python

Java
Python
Python
-- Roy Lau

Python
Python
-- Samuel Young

Swaroop
O'Reilly Python Learning Python

Python

-- Joseph Duarte

Python
-- Chris-Andr Sommerseth


Python

Python

-- myd7349

Python
Python pyGame
Python
Python

OOP
-- Matt Gallivan

Python
Ahmed15Python
Visual Basic 6 Python

Python
Java Java
-- Ahmed Mohammed

Swaroop C H Python 110 PDF


Python
Python -- Drew Ames

N800 Python
Python Python --
Jason Delport

@swaroopch Vim Byte of Vim Python


#FeelGoodFactor --
Surendran

Python
Python -- Justin LoveTrue

Python:) Chinmay

Python
-- Patrick Harrington

Python
:) --
Gadadhari Bheem

Python AssemblyCC++C# Java


Python
Swaroop
Python 10 -- Fang Biyi (
)

Python
OO
Python

-- Bob

Python

-- "The Walrus"

Python 2 3
Python
Yotube





-- Chris

2011 Python
Python
Python
Python

C C++Augmented
Assignment

C C++







Python




-- Nick

Ankush19 Python

Python -- Ankush

Python
DNA
Python
:) -- Luca

Python Python
Python
-- "{Unregistered}"

Python
Vim A Byte of Vim

-- Jocimar

3 Python
Orca
-- Dattatray

Python Python
4 Java C
Zim-Wiki pygtk 6
Python
-- Lee

Isen
Python
GNU Radio
--
Isen I-Chun Chao

NASA NASA Jet Propulsion Laboratory

Principles of Programming Languages



Basic Concepts of Computing

Python Programming With Python
Introduction to Programming
Introduction to Application Programming
Information Technology Skills for
Meteorology
Geoprocessing
Web Multi Agent Semantic Web Systems
MIT MIT OpenCourseWare Introduction to
Computer Science and Programming
Basic Programming --
Ale iberna
Introduction to programming
-- Kreimir Zauder Python

Swaroop C H Byte of PythonByte of Python


- 4.0 CC BY-SA Intl. 4.0

- 4.0 CC BY-SA Intl.


4.0




http://python.swaroopch.com/ https://bop.molun.net

3-clause BSD License

http://python.swaroopch.com/

https://bop.molun.net

http://www.swaroopch.com/buybook/

https://www.gitbook.com/book/lenkimo/byte-of-python-chinese-edition/

PDF
EPUB iPhoneiPad
Mobi Kindle

GitBook GitBook

Markdown https://github.com/LenKiMo/byte-of-python

http://python.swaroopch.com/
https://github.com/swaroopch/byte-of-python

Kalyan Varma PESIT


GNU/Linux

Atul Chitnis

2003

10

Python
Python

Python

Python Python

Python
Python

http://python.swaroopch.com/

https://bop.molun.net



C. A. R. Hoare

C. W. Wendte

11

Python
PythonSwaroop C H A Byte of Python
Python

Python

2005 Byte of Python 1.20


Python
Python

11 Byte of Python
Python Python 2 Python 3
print 'hello world' Python 3
Python

Python 2 3

Python

Byte of Python GitHub


4.0c
.py

1.20 CC BY-NC-ND 1.0--


--

12

Nakagawa KanonZxteloivYukko

SwaroopC
Hblog@swaroopch.com
i@molun.net

Python

201712

2017 1 3 1 8 anglum slimray


2001
lefinite Zhanyu Wang
nonozone
ivysrono 4.01c

2017 1 9 2 16 Haruki
KirigayaYuki KiriyamaNakagawa Kanon
Cloud yurikaka
aristotll Tian
Zhao 4.02c

13

2017 3 19 Tian Zhao


yangyangwithgnu
FLOSSYang
4.03c

2017 5 1 Nangcr
Haruki KirigayaYuki Kiriyamashuven
4.04c

14
Python

Python
Python

Python

Python
Python

Python Guido van Rossum BBC


Monty Python's Flying Circus

Python

Python Python
Python

Python Python

15
Python

Python FLOSS /

FLOSS Python
Python

Python

Python
Python

GNU/LinuxWindowsFreeBSDMacintosh Solaris OS/2 Amiga


AROS AS/400 BeOS OS/390 z/OS Palm OS QNX VMS Psion Acorn
RISC OS VxWorks PlayStation Sharp Zaurus Windows CE PocketPC
Python

Kivy iPhoneiPad

C C++
Flags 0 1

Python
Python
Python
Python
Python

16
Python

Python

C++ Java Python

C C++ Python

C C++ Python

Python
CGIFTPXMLXML-RPC
HTMLWAV GUI
Python Python
Batteries Included

Python Python Package Index

Python
Python

Python 3 VS Python 2
Python 2Python 3
Python 3

Python
Python

Pyhon 2 Python 3

Python 2 Python 3

The future of Python 2

17
Python

Porting Python 2 Code to Python 3


Writing code that runs under both Python2 and 3
Supporting Python 3: An in-depth guide

ESR Python

Eric S. Raymond The Cathedral and the


Bazaar Python
Python
Bruce Eckel Java Thinking in JavaC++
Thinking in C++ Python
Python

Peter Norvig Lisp Google
Director of Search Quality Python
Python Google
Google Jobs Python

18

Python 3 Python 3.5.11

Windows
https://www.python.org/downloads/ Python
Python 3.5.1 Windows

Add Python 3.5 to PATH

Customize installation Next


C:\python35

Add Python to environment variables


Add Python 3.5 to PATH

Python

Path
Windows Python

Docker Python in Docker


Docker on Windows

DOS
Windows Python DOS PATH

Windows 2000XP2003
PATH ;C:\Python35
Python

Windows C:\AUTOEXEC.BAT
PATH=%PATH%;C:\Python35 Windows NT

AUTOEXEC.NT

Windows Vista

19



Vista

Windos 7 8



PATH

;C:\Python35
Python

%SystemRoot%\system32;
%SystemRoot%\system32;C:\Python35

Windows Python
Windows PATH

Windows cmd

python

Mac OS
Mac OS X Homebrew brew install python3

[Command + Space] Spotlight


Terminal [enter] python3

GNU/Linux
GNU/Linux Python 3 Debian
Ubuntu sudo apt-get update && sudo apt-get install python3

20

Terminal Alt + F2
gnome-terminal GNU/Linux
python3

Python

$ python3 -V
Python 3.5.1

$ Shell
$

Python

Python

Python

1. Python 3.5.1 Python

Python 3.5.1

21

Python Hello World


Python

Python

Terminal
python3 [enter] Python Python Prompt

Python >>> Python


Python Interpreter Prompt

Python

print("Hello World")

[enter] Hello World

Mac OS X Python
>>>

> python3
Python 3.5.1 (default, Jan 14 2016, 06:54:11)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World")
Hello World

Python
Python print
Hello World

22

GNU/Linux OS X Shell [ctrl + d]


exit() () [enter]

Windows [ctrl + z] [enter]

Python

Python


Python

PyCharm Windows
Mac OS XGNU/Linux

Windows

Vim Emacs
Python
Entire Book on Vim

Vim Emacs

PyCharm Python

Python

PyCharm
PyCharm Python

23

PyCharm Create New Project

Pure Python

24

untitled helloworld

Create

helloworld New -> Python File

hello

25

print("hello world")

Run 'hello'

26

helloworld -> New -> Python File

PyCharm Quickstart PyCharm

Vim
1. Vim
Mac OS X HomeBrew macvim
Windows Vim

27

GNU/Linux Vim Debian


Ubuntu vim
2. jedi-vim Vim
3. jedi Python pip install -U jedi

Emacs
1. Emacs 24+
Mac OS X http://emacsformacosx.com Emacs
Windows http://ftp.gnu.org/gnu/emacs/windows/ Emacs
GNU/Linux Emacs Debian
Ubuntu emacs24
2. ELPY

Hello World Hello


WorldSimon Cozens 1

hello.py

PyCharm

hello.py

print("hello world")

Python

Mac OS X /tmp/py
GNU/Linux /tmp/py
Windows C:\\py

mkdir
mkdir /tmp/py

.py foo.py

Python

28

1.
2. cd cd /tmp/py
3. python hello.py

$ python hello.py
hello world

Python

Python print Print p


P

Python
print hello world

Python help
help('len')
len

29

Python help()
help

return
help('return') Python

Python

Python Python

1. Beginning Perl

30

hello world
Python
1

print('hello world') # print

# print
print('hello world')

2
Literal Constants 5 1.23
This is a string

31

3

2

IntegersFloats

Floating Point Numbers floats 3.23


52.3E-4 E 10 52.3E-4 52.3 * 10^-4

long int

String Characters Sequence

Python

'' 'Quote me on this'

""
"What's your name?"

""" '''

32

'''
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''

C/C++

Python char

Perl/PHP

format()

str_format.py

age = 20
name = 'Swaroop'

print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))

$ python str_format.py
Swaroop was 20 years old when he wrote this book
Why is Swaroop playing with that python?

Specification format

{0} name
{1} age
Python 0 0

33

name + 'is' +str(age) + 'years old'

format
format

age = 20
name = 'Swaroop'

print('{} was {} years old when he wrote this book'.format(name, age))


print('Why is {} playing with that python?'.format(name))

Python format

# '0.333' (.)
print('{0:.3f}'.format(1.0/3))
#
# (^) '___hello___' 11
print('{0:_^11}'.format('hello'))
# 'Swaroop wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))

0.333
___hello___
Swaroop wrote A Byte of Python

print \n
print
end

print('a', end='')
print('b', end='')

34

ab

end

print('a', end=' ')


print('b', end=' ')
print('c')

a b c

'
"What's your name?" 'What's your name?'
Python
Escape Sequence
\ 'What\'s your

name?'

"What's your name?"



\\

\n

'This is the first line\nThis is the second line'

\t

"This is the first sentence. \


This is the second sentence."

35

"This is the first sentence. This is the second sentence."

4
r R Raw

r"Newlines are indicated by \n"

Backwhacking
'\\1' r'\1'

Veriables

Identifiers

ASCII ASCII Unicode


_
ASCII ASCII Unicode
_ 0~9
myname myName
n N
i name_2_3
2things this is spaced out my-name >a1b2_c3

36

Data Type
Classes

Python Object
objectsomething

Python Strongly

Python
Python

PyCharm
1. PyCharm
2.
3.
4.

Command Line Arguments Run -> Edit


Configurations Script parameters: OK

37

1.
2.
3.
4. python program.py

# var.py
i = 5
print(i)
i = i + 1
print(i)

s = '''This is a multi-line string.


This is the second line.'''
print(s)

38

5
6
This is a multi-line string.
This is the second line.

= 5
i Statement
i 5 print
i

1 i
6

Physical Line Logical


Line Python Python

print('hello world')

Python Python

( ; )

i = 5
print(i)

i = 5;
print(i);

39

i = 5; print(i);

i = 5; print(i)

Python

Explicit Line Joining5

s = 'This is a string. \
This continues the string.'
print(s)

This is a string. This continues the string.

i = \
5

i = 5

Implicit Line
JoiningList

6 Python
Indentation

40

block

i = 5
#
print('Value is', i)
print('I repeat, the value is', i)

File "whitespace.py", line 3


print('Value is', i)
^
IndentationError: unexpected indent
#

Python

Python

Python from
__future__ import braces

1.

41

2. Literal Constants

Python Literal
3. literal

4. Raw String

5.

6. Whitespace

Space

42

Expressions
2+3 OperatorsOperands

Operators +
Operands
2 3

2+3 Python

>>> 2 + 3
5
>>> 3 * 5
15
>>>


3+5 8 'a' + 'b' 'ab'


-5.2 50 - 24 26


2 * 3 6 'la' * 3 'lalala'

**

x y
3 ** 4 81 3 * 3 * 3 * 3

43

x y
13 / 3 4.333333333333333

//

x y
13 // 3 4

-13 // 3 -5


13 % 3 1 -25.5 % 2.25 1.5

<<

0 1
2 << 2 8 2 10

2 1000 8
>>


11 >> 1 5

11 1011 101

&

1
5 & 3 1

2
5 | 3 7

3
5 ^ 3 6
4
~

x -(x+1)
~5 -6

http://stackoverflow.com/a/11810203
<

x y True False

5 < 3 False 3 < 6 True

44

3 < 5 < 7 True


>

x y
5 > 3 True

False
<=

x y
x = 3; y = 6; x<=y True

>=

x y
x = 4; y = 3; x>=3 True

==


x = 2; y = 2; x == y True

x = 'str'; y = 'stR'; x == y False

x = 'str'; y = 'str'; x == y True

!=


x = 2; y = 3; x != y True
5
not

x Ture False x False True


x = Ture; not x False
6
and

x False x and y False y


x False x = False; y = True; x and y False
Python y and False
False Short-circuit
Evaluation
7
or

x True True y
x = Ture; y = False; x or y Ture

45

a = 2
a = a * 3

a = 2
a *= 3

= =

2 + 3 * 4

Python
Python

Python

lambda Lambda

if - else

or

and

not x

in, not in, is, is not, <, <=, >, >=, !=, ==

Membership TestsIdentity Tests


|

&

<<, >>

+, -

*, /, //, %

+x, -x, ~x

**

46

x[index], x[index:index], x(arguments...), x.attribute


(expressions...), [expressions...], {key: value...}, {expressions...}

+ -

2 + (3 * 4) 2 + 3 * 4

(2 + (3 * 4))

(2 + 3) * 4

2 + 3 + 4 (2 + 3) +4

expression.py

length = 5
breadth = 2

area = length * breadth


print('Area is', area)
print('Perimeter is', 2 * (length + breadth))

$ python expression.py
Area is 10
Perimeter is 14

47

LengthBreadth
AreaPerimeter length *
breadth area print

print 2 * (length + breadth)

Python Area
is area Python

Python

1.

1 1 0 5 101 3
11 011
001 1

2.

1 1 0 101 011
111 7
3.

1 0 101 011
110 6
4.

0 1 1
0


5. Boolean NOT

6. Boolean AND

7. Boolean OR

8. Evaluation Order

9. Associativity

48

49

Python

''
'Good Morning' '' 'Good Evening'

Python
if for while

if

if True if-block if

else-block else else

if.py

number = 23
guess = int(input('Enter an integer : '))

if guess == number:
#
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
#
elif guess < number:
#
print('No, it is a little higher than that')
#
else:
print('No, it is a little lower than that')
# >

print('Done')
#
# if

50

$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done

$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done

$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done

number 23 input()

input
enter input()
int guess
int Class

Python
Python

if Python

elif if else-if
else if-elif-else

elif else

if if if
if

51

elif else if

if True:
print('Yes, it is true')

Python if elif else


if

print('Done') Python

C/C++

C/C++

Python switch if..elif..else


while

while while

Looping while else

while.py

52

number = 23
running = True

while running:
guess = int(input('Enter an integer : '))

if guess == number:
print('Congratulations, you guessed it.')
# while
running = False
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
#

print('Done')

$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

while

input if while while


running True running True

while
running True while

else

else while False

while else
break

53

True False Bollean 1 0

C/C++

while else

for

for...in Iterates

Sequences

for.py

for i in range(1, 5):


print(i)
else:
print('The for loop is over')

$ python for.py
1
2
3
4
The for loop is over

range

range
range(1,5) [1, 2, 3, 4]
range 1 range
range(1,5,2) [1, 3]

range()
range() list() list(range(5)) [0, 1, 2,
3, 4]

54

for for i in range(1,5) for i in [1,


2, 3, 4] i

else for
break

for...in
range

C/C++/Java/C#

Python for C/C++ for C#


Python for C# foreach Java
Java 1.5 for (int i : IntArray)

C/C++ for (int i = 0; i < 5; i++) Python


for i in range(0,5) Python for

break

break Break

False

for while
else

break.py

while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')

55

$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something : use Python!
Length of the string is 11
Enter something : quit
Done

quit

len

break for

Swaroop Python

Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

continue

continue Python

continue.py

56

while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
#

$ python continue.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit

3
len
3 continue

continue for

if while for break


continue Python

57

Functions

Calling len range

def

functon1.py

def say_hello():
#
print('hello world')
#

say_hello() #
say_hello() #

$ python function1.py
hello world
hello world

say_hello

58

Parameters
Arguments

function_param.py

def print_max(a, b):


if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')

#
print_max(3, 4)

x = 5
y = 7

#
print_max(x, y)

$ python function_param.py
4 is maximum
7 is maximum

print_max a b
if...else

print_max
print_max(x, y) x
a y b print_max

59

Local
Scope

function_local.py

x = 50

def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)

func(x)
print('x is still', x)

$ python function_local.py
x is 50
Changed local x to 2
x is still 50

x Python

2 x x
x x

print x

global

Python Global
global global

60

global

function_global.py

x = 50

def func():
global x

print('x is', x)
x = 2
print('Changed global x to', x)

func()
print('Value of x is', x)

$ python function_global.py
x is 50
Changed global x to 2
Value of x is 2

global x x

global global x, y, z

function_default.py

61

def say(message, times=1):


print(message * times)

say('Hello')
say('World', 5)

$ python function_default.py
Hello
WorldWorldWorldWorldWorld

say
times 1

say
say 5 Say

def func(a, b=5)


def func(a=5, b)

Keyword Arguments

`function_keyword.py

62

def func(a, b=5, c=10):


print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)

$ python function_keyword.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

func

func(3, 7) a 3 b 7 c
10

func(25, c=24) a 25
c 24 b
5

func(c=50, a=100)
a c a c

function_varargs.py

def total(a=5, *numbers, **phonebook):


print('a', a)

#
for single_item in numbers:
print('single_item', single_item)

#
for first_part, second_part in phonebook.items():
print(first_part,second_part)

print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))

63

$ python function_varargs.py
a 10
single_item 1
single_item 2
single_item 3
Inge 1560
John 2231
Jack 1123
None

*param
Positional ArgumentsparamTuple

**param
param Dictionary

return

return

function_return.py

def maximum(x, y):


if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y

print(maximum(2, 3))

$ python function_return.py
3

64

maximum

if...else

return None None Python



None

return None return


print(some_function()) some_function return

def some_function():
pass

Python pass

max

DocStrings
Python Documentation Strings
docstringsDocStrings

function_docstring.py

def print_max(x, y):


'''Prints the maximum of two numbers.

The two values must be integers.'''


#
x = int(x)
y = int(y)

if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')

print_max(3, 5)
print(print_max.__doc__)

65

$ python function_docstring.py
5 is maximum
Prints the maximum of two numbers.

The two values must be integers.

DocString
ModulesClass

__doc__
print_max Python
Class

Python help()
__doc__
help(print_max) q
help

Python pydoc help()

Python

Python

1. Function ParametersParameter Argument


Parameter
2. Local Varibles

3. Keyword Arguments

66

4. VarArgs ParametersVarArgs

Variable Arguments
5.

67

Modules

.py

Python C
Python Python Python

Python

( module_using_sys.py ):

import sys

print('The command line arguments are:')


for i in sys.argv:
print(i)

print('\n\nThe PYTHONPATH is', sys.path, '\n')

$ python module_using_sys.py we are arguments


The command line arguments are:
module_using_sys.py
we
are
arguments

The PYTHONPATH is ['/tmp/py',


# many entries here, not shown here
'/Library/Python/2.7/site-packages',
'/usr/local/lib/python2.7/site-packages']

68

import sys Python


sys Python
system

Python import sys sys


Python

Python Python
sys.path

sys argv sys.argv

sys
argv

sys.argv List

sys.argv Command Line Arguments

IDE

python module_using_sys.py we are arguments python


module_using_sys.py Python
sys.argv

sys.argv
'module_using_sys.py' sys.argv[0] 'we'
sys.argv[1] 'are' sys.argv[2] 'arguments' sys.argv[3]

Python 0 1

sys.path sys.path

sys.path PYTHONPATH

sys.path

import os;
print(os.getcwd())

.pyc 1

69

Python
Byte-Compiled .pyc
Python Python
.pyc

.pyc .py Python


.pyc

from..import

argv sys.
from sys import argv

from...import import

from math import sqrt


print("Square root of 16 is", sqrt(16))

__name__

__name__

module_using_name.py

if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module')

70

$ python module_using_name.py
This program is being run by itself

$ python
>>> import module_using_name
I am being imported from another module
>>>

Python __name__ __main__

Python
.py

mymodule.py

def say_hi():
print('Hi, this is mymodule speaking.')

__version__ = '0.1'

Python
Python

sys.path

mymodule_demo.py

import mymodule

mymodule.say_hi()
print('Version', mymodule.__version__)

$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1

71

Python
Pythonic

from...import mymodule_demo2.py

from mymodule import say_hi, __version__

say_hi()
print('Version', __version__)

mymodule_demo2.py mymodule_demo.py

mymodule __version__

import

from mymodule import *

say_hi __version__

import `from mymodule import `

Python

Python 2 Python import this


dir

dir()

72

$ python
>>> import sys

# sys
>>> dir(sys)
['__displayhook__', '__doc__',
'argv', 'builtin_module_names',
'version', 'version_info']
# only few entries shown here

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

# 'a'
>>> a = 5

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

#
>>> del a

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

dir sys

dir

dir a
dir del

dir

del
del a a

dir() dir(str) str String

vars()

73

Packages

__init__.py Python
Python

world asiaafrica
indiamadagascar

- <some folder present in the sys.path>/


- world/
- __init__.py
- asia/
- __init__.py
- india/
- __init__.py
- foo.py
- africa/
- __init__.py
- madagascar/
- __init__.py
- bar.py

Python

1. Byte-compiled .pyc Files .pyc

2
. Explicit is better than Implicit

74

75

Data Structures

Python ListTupleDictionary
Set

Python

Python

Mutable

ObjectClass

i 5
int i
help(int)

Method
Python list
append mylist.append('an item')
mylist

Field

mylist.field

ds_using_list.py

76

# This is my shopping list


shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase.')

print('These items are:', end=' ')


for item in shoplist:
print(item, end=' ')

print('\nI also have to buy rice.')


shoplist.append('rice')
print('My shopping list is now', shoplist)

print('I will sort my list now')


shoplist.sort()
print('Sorted shopping list is', shoplist)

print('The first item I will buy is', shoplist[0])


olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)

$ python ds_using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

shoplist shoplist

for...in

print end

77

append
print

sort

MutableImmutable

del del

del shoplise[0] Python 0

help(list)

Tuple

ds_using_tuple.py

#
#
#
#
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))

new_zoo = 'monkey', 'camel', zoo


print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',
len(new_zoo)-1+len(new_zoo[2]))

78

$ python ds_using_tuple.py
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5

zoo len

Zoo new_zoo

Indexing
new_zoo[2] new_zoo new_zoo[2][2]

new_zoo
1

0 1

myempty = ()

Python
2
singleton = (2, )

Perl

Perl Flattened
Python

KeysValues

79

d = {key : value1 , key2 : value2}

dict

ds_using_dict.py

# abAddressBook

ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}

print("Swaroop's address is", ab['Swaroop'])

#
del ab['Spammer']

print('\nThere are {} contacts in the address-book\n'.format(len(ab)))

for name, address in ab.items():


print('Contact {} at {}'.format(name, address))

#
ab['Guido'] = 'guido@python.org'

if 'Guido' in ab:
print("\nGuido's address is", ab['Guido'])

80

$ python ds_using_dict.py
Swaroop's address is swaroop@swaroopch.com

There are 3 contacts in the address-book

Contact Swaroop at swaroop@swaroopch.com


Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org

Guido's address is guido@python.org

ab

del
del

item

for...in name
address for

Guido

in

dict help(dict)




Symbol Table

Sequence

81

Membership Test in not in


Indexing Operations

Slicing

ds_seq.py

shoplist = ['apple', 'mango', 'carrot', 'banana']


name = 'swaroop'

# Indexing or 'Subscription' operation #


# Subcription #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Character 0 is', name[0])

# Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])

# #
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

82

$ python ds_seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Character 0 is s
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop

Subscription OperationPython
Python 0 shoplist[0]
shoplist shoplist[3]

shoplist[-1] shoplist[-2]

Python
Python
start end

shoplist[1:3] 1 2 3
shoplist[:]

shoplist[:-1]

Step
1

83

>>> shoplist = ['apple', 'mango', 'carrot', 'banana']


>>> shoplist[::1]
['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::2]
['apple', 'carrot']
>>> shoplist[::3]
['apple', 'banana']
>>> shoplist[::-1]
['banana', 'carrot', 'mango', 'apple']

2 024 3
03

Python

SetCollection

>>> bri = set(['brazil', 'russia', 'india'])


>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}

84

Refer

Binding

ds_reference.py

print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist
mylist = shoplist

#
del shoplist[0]

print('shoplist is', shoplist)


print('mylist is', mylist)
# shoplist mylist
# apple
#

print('Copy by making a full slice')


#
mylist = shoplist[:]
#
del mylist[0]

print('shoplist is', shoplist)


print('mylist is', mylist)
#

$ python ds_reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

85

Object

Perl

str
help(str)

ds_str_methods.py

#
name = 'Swaroop'

if name.startswith('Swa'):
print('Yes, the string starts with "Swa"')

if 'a' in name:
print('Yes, it contains the string "a"')

if name.find('war') != -1:
print('Yes, it contains the string "war"')

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))

$ python ds_str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China

86

startwith
in

find find

-1 str Join

Python
Python

Python
Python

1.

2. Reference

87

Python

Python

Analysis
?

Design



zip
zip
GNU/Linux Unix zip

Windows

Windows GnuWin32 zip C:\Program


Files\GnuWin32\bin PATH

Python

Implementation

88

backup_ver1.py

import os
import time

# 1.
#
# Windows
# source = ['"C:\\My Documents"', 'C:\\Code']
# Mac OS X Linux
source = ['/Users/swa/notes']
#
#

#2.
#
# Windows
# target_dir = 'E:\\Backup'
# Mac OS X Linux
target_dir = '/Users/swa/backup'
#

# 3. zip
# 4. zip
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'

#
if not os.path.exists(target_dir):
os.mkdir(target_dir) #

# 5. zip zip
zip_command = 'zip -r {0} {1}'.format(target,
' '.join(source))

#
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')

89

$ python backup_ver1.py
Zip command is:
zip -r /Users/swa/backup/20140328084844.zip /Users/swa/notes
Running:
adding: Users/swa/notes/ (stored 0%)
adding: Users/swa/notes/blah1.txt (stored 0%)
adding: Users/swa/notes/blah2.txt (stored 0%)
adding: Users/swa/notes/blah3.txt (stored 0%)
Successful backup to /Users/swa/backup/20140328084844.zip

Testing
Debug
Bug

Zip command is
shell GNU/Linux Mac OS X cmd Windows
zip
Python

os time source
target_dir
zip
time.strftime() .zip target_dir

os.sep
GNU/Linux Unix '/' Windows '\\' Mac OS
':' os.sep

time.strftime() Specification

%Y %m 01 12
Python

Concatenates + zip

zip_command
ShellGNU/Linux DOS

90

zip -r zip
Recursively
-qr zip

join source

os.system
shell 0

Windows

'C:\\Documents'
r'C:\Documents' 'C:\Documents'

\D

OperationDeployment

Debug

Maintenance

backup_ver2.py

91

import os
import time

# 1.
#
# Windows
# source = ['"C:\\My Documents"', 'C:\\Code']
# Mac OS X Linux
source = ['/Users/swa/notes']
#
#

# 2.
#
# Windows
# target_dir = 'E:\\Backup'
# Mac OS X Linux
target_dir = '/Users/swa/backup'
#

#
if not os.path.exists(target_dir):
os.mkdir(target_dir) #

# 3. zip
# 4.
today = target_dir + os.sep + time.strftime('%Y%m%d')
# zip
now = time.strftime('%H%M%S')

# zip
target = today + os.sep + now + '.zip'

#
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)

# 5. zip zip
zip_command = 'zip -r {0} {1}'.format(target,
' '.join(source))

#
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')

92

$ python backup_ver2.py
Successfully created directory /Users/swa/backup/20140329
Zip command is:
zip -r /Users/swa/backup/20140329/073201.zip /Users/swa/notes
Running:
adding: Users/swa/notes/ (stored 0%)
adding: Users/swa/notes/blah1.txt (stored 0%)
adding: Users/swa/notes/blah2.txt (stored 0%)
adding: Users/swa/notes/blah3.txt (stored 0%)
Successful backup to /Users/swa/backup/20140329/073201.zip

os.path.exists
os.mkdir

zip

backup_ver3.py

import os
import time

# 1.
#
# Windows
# source = ['"C:\\My Documents"', 'C:\\Code']
# Mac OS X Linux
source = ['/Users/swa/notes']
#
#

# 2.
#
# Windows
# target_dir = 'E:\\Backup'

93

# Mac OS X Linux
target_dir = '/Users/swa/backup'
#

#
if not os.path.exists(target_dir):
os.mkdir(target_dir) #

# 3. zip
# 4.
#
today = target_dir + os.sep + time.strftime('%Y%m%d')
# zip
now = time.strftime('%H%M%S')

#
# zip
comment = input('Enter a comment --> ')
#
if len(comment) == 0:
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' +
comment.replace(' ', '_') + '.zip'

#
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)

# 5. zip zip
zip_command = "zip -r {0} {1}".format(target,
' '.join(source))

#
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')

$ python backup_ver3.py
File "backup_ver3.py", line 39
target = today + os.sep + now + '_' +
^
SyntaxError: invalid syntax

94

Python Python
Python
Debug

Python +

Bug Fixing

backup_ver4.py

import os
import time

# 1.
#
# Windows
# source = ['"C:\\My Documents"', 'C:\\Code']
# Mac OS X Linux
source = ['/Users/swa/notes']
#
#

# 2.
#
# Windows
# target_dir = 'E:\\Backup'
# Mac OS X Linux
target_dir = '/Users/swa/backup'
#

#
if not os.path.exists(target_dir):
os.mkdir(target_dir) #

# 3. zip
# 4.
#
today = target_dir + os.sep + time.strftime('%Y%m%d')
# zip
now = time.strftime('%H%M%S')

#
# zip

95

comment = input('Enter a comment --> ')


#
if len(comment) == 0:
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'

#
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)

# 5. zip zip
zip_command = 'zip -r {0} {1}'.format(target,
' '.join(source))

#
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')

$ python backup_ver4.py
Enter a comment --> added new examples
Zip command is:
zip -r /Users/swa/backup/20140329/074122_added_new_examples.zip /Users/swa/notes
Running:
adding: Users/swa/notes/ (stored 0%)
adding: Users/swa/notes/blah1.txt (stored 0%)
adding: Users/swa/notes/blah2.txt (stored 0%)
adding: Users/swa/notes/blah3.txt (stored 0%)
Successful backup to /Users/swa/backup/20140329/074122_added_new_examples.zip

input len
enter

96

zip
.zip

-v 1
-q Quiet

sys.argv list extend

source .

os.system zipfile tarfile


zip

os.system

zipfile os.system

Phases

1. What/
2. How/
3. Do It/
4. Test/
5. Use/
6. Maintain/

97

Software is grown, not built. Bill de


hra

Python

Python

1. Verbosity

98

Procedure-oriented

Class
TypeObjectInstance
int int

int C++ Java1.5


1

help(int)

C# Java 1.5 Boxing and Unboxing2


Field
Method
Attribute

Instance VariablesClass Variables

class

self

Python
self

self

IDEIntegrated Development Environments


self

99

C++/Java/C#

Python self C++ Java C# this

Python self
MyClass myobject
myobject.method(arg1, arg2) Python
MyClass.method(myobject, arg1, arg2) self

self

Class oop_simplestclass.py

class Person:
pass #

p = Person()
print(p)

$ python oop_simplestclass.py
<__main__.Person instance at 0x10171f518>

class
pass

Person __main__

Python

100

Method
self
oop_method.py

class Person:
def say_hi(self):
print('Hello, how are you?')

p = Person()
p.say_hi()
#
# Person().say_hi()

$ python oop_method.py
Hello, how are you?

self say_hi
self

__init__

Python __init__

__init__ Instantiated

Initialization init

oop_init.py

class Person:
def __init__(self, name):
self.name = name

def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Swaroop')
p.say_hi()
#
# Person('Swaroop').say_hi()

101

$ python oop_init.py
Hello, my name is Swaroop

__init__ name self


name name
self.name
nameself name

Person p
p = Person('Swaroop')

__init__

self.name say_hi

BoundNamespace

Filed

Class VariableShared

Object variable

oop_objvar.py

# coding=UTF-8

class Robot:
""""""

102

#
population = 0

def __init__(self, name):


""""""
self.name = name
print("(Initializing {})".format(self.name))

#
#
Robot.population += 1

def die(self):
""""""
print("{} is being destroyed!".format(self.name))

Robot.population -= 1

if Robot.population == 0:
print("{} was the last one.".format(self.name))
else:
print("There are still {:d} robots working.".format(
Robot.population))

def say_hi(self):
"""

"""
print("Greetings, my masters call me {}.".format(self.name))

@classmethod
def how_many(cls):
""""""
print("We have {:d} robots.".format(cls.population))

droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()

droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many()

print("\nRobots can do some work here.\n")

print("Robots have finished their work. So let's destroy them.")


droid1.die()
droid2.die()

Robot.how_many()

103

$ python oop_objvar.py
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.

Robots can do some work here.

Robots have finished their work. So let's destroy them.


R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.

population
Robot name self

Robot.population self.population population


name self.name

Robot.popluation self.__class__.population
self.__class__

how_many

classmethod staticmethod

classmethod

Decorator how_many

Wrapper
@classmethod

how_many = classmethod(how_many)

104

__init__ Robot
population 1 self.name

self Attribute
Reference

DocStrings
Robot.__doc__
Robot.say_hi.__doc__

die Robot.population 1

__privatervar Python Name-


mangling

Python

C++/Java/C#

Python
Vireual

Reuse
InheritanceType and Subtype

SchoolMember
Inherit

105

SchoolMember
SchoolMember
ID
SchoolMember
Polymorphism

SchoolMember Base Class4


Superclass Teacher Student Derived Classes5
Subclass

oop_subclass.py

106

# coding=UTF-8

class SchoolMember:
''''''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {})'.format(self.name))

def tell(self):
''''''
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")

class Teacher(SchoolMember):
''''''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {})'.format(self.name))

def tell(self):
SchoolMember.tell(self)
print('Salary: "{:d}"'.format(self.salary))

class Student(SchoolMember):
''''''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('(Initialized Student: {})'.format(self.name))

def tell(self):
SchoolMember.tell(self)
print('Marks: "{:d}"'.format(self.marks))

t = Teacher('Mrs. Shrividya', 40, 30000)


s = Student('Swaroop', 25, 75)

#
print()

members = [t, s]
for member in members:
#
member.tell()

107

$ python oop_subclass.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)

Name:"Mrs. Shrividya" Age:"40" Salary: "30000"


Name:"Swaroop" Age:"25" Marks: "75"

6
__init__ self
Teacher Student
__init__ Python SchoolMember

__init__ Python

self

SchoolMember tell Teacher


Studtne SchoolMember

tell SchoolMember tell


Python

Inheritance Tuple
Multiple Inheritance

end tell() print

print \n

Python

108

Python

1. Primitive native typesPrimitive

type
2.

3. Class And Object Variables

4.

5.

6.

109

input() print

str String
rjust help(str)

io_input.py

def reverse(text):
return text[::-1]

def is_palindrome(text):
return text == reverse(text)

something = input("Enter text: ")


if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")

$ python3 io_input.py
Enter text: sir
No, it is not a palindrome

$ python3 io_input.py
Enter text: madam
Yes, it is a palindrome

$ python3 io_input.py
Enter text: racecar
Yes, it is a palindrome

110

seq[a:b] a
b
Step 1 -1

input()

input()

Rise to vote, sir.

file read readline write

close Python

io_using_file.py

111

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''

# 'w'riting
f = open('poem.txt', 'w')
#
f.write(poem)
#
f.close()

#
# 'r'ead
f = open('poem.txt')
while True:
line = f.readline()
# EOF
if len(line) == 0:
break
# `line`
#
#
print(line, end='')
#
f.close()

$ python3 io_using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

open
'r' 'w' 'a'
't' 'b'
help(open)
open() textread

write
close

112

readline

break

close

poem.txt

2
Pickle
Python Pickle Python
Persistently

io_pickle.py

import pickle

# The name of the file where we will store the object


shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['apple', 'mango', 'carrot']

# Write to the file


f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f)
f.close()

# Destroy the shoplist variable


del shoplist

# Read back from the storage


f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f)
print(storedlist)

$ python io_pickle.py
['apple', 'mango', 'carrot']

113

open write
binary pickle dump
Pickling

pickle load
Unpickling

3
Unicode

Python 2
unicode u u"hello world"

>>> "hello world"


'hello world'
>>> type("hello world")
<class 'str'>
>>> u"hello world"
'hello world'
>>> type(u"hello world")
<class 'str'>

Unicode UTF-8
open

# encoding=utf-8
import io

f = io.open("abc.txt", "wt", encoding="utf-8")


f.write(u"Imagine non-English language here")
f.close()

text = io.open("abc.txt", encoding="utf-8").read()


print(text)

import

Unicode Python
UTF-8 # encoding=urf-8
4

114

io.open EncodingDecoding Python


Unicode

"The Absolute Minimum Every Software Developer Absolutely, Positively Must Know
About Unicode and Character Sets"
Python Unicode Howto
Pragmatic Unicode talk by Nat Batchelder

pickle
Unicode

1.

forbidden = ( ! ,
? , . , ...)

2.


3. Unicode


4
. UTF-8

Python

115

Exception

Python
Raises1Error

print print Print


Python Raise

>>> Print("Hello World")


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Print' is not defined
>>> print("Hello World")
Hello World

NameError Python
2
Error Handler

Try [ctrl-d]

>>> s = input('Enter something --> ')


Enter something --> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError

Python EOFError End of


File ctrl-d

116

try..except try
except

exceptions_handle.py

try:
text = input('Enter something --> ')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
else:
print('You entered {}'.format(text))

# Press ctrl + d
$ python exceptions_handle.py
Enter something --> Why did you do an EOF on me?

# Press ctrl + c
$ python exceptions_handle.py
Enter something --> ^CYou cancelled the operation.

$ python exceptions_handle.py
Enter something --> No exceptions
You entered No exceptions

try
Handler except except

except try try

Python

else try..except else

3
117

raise
Thrown

Exception

exceptions_raise.py

# encoding=UTF-8

class ShortInputException(Exception):
''''''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast

try:
text = input('Enter something --> ')
if len(text) < 3:
raise ShortInputException(len(text), 3)
#
except EOFError:
print('Why did you do an EOF on me?')
except ShortInputException as ex:
print(('ShortInputException: The input was ' +
'{0} long, expected at least {1}')
.format(ex.length, ex.atleast))
else:
print('No exception was raised.')

$ python exceptions_raise.py
Enter something --> a
ShortInputException: The input was 1 long, expected at least 3

$ python exceptions_raise.py
Enter something --> abc
No exception was raised.

ShortInputException
length atleast

118

except as
except length
atlease

Try ... Finally

finally

exceptions_finally.py

import sys
import time

f = None
try:
f = open("poem.txt")
#
while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
sys.stdout.flush()
print("Press ctrl+c now")
#
time.sleep(2)
except IOError:
print("Could not find file poem.txt")
except KeyboardInterrupt:
print("!! You cancelled the reading from the file.")
finally:
if f:
f.close()
print("(Cleaning up: Closed the file)")

$ python exceptions_finally.py
Programming is fun
Press ctrl+c now
^C!! You cancelled the reading from the file.
(Cleaning up: Closed the file)

119

time.sleep
Python
ctrl + c

KeyboardInterrupt finally

print sys.stout.flush()

with

try finally
with

exceptions_using_with.py

with open("poem.txt") as f:
for line in f:
print(line, end='')

open
with with open

with Protocol open


thefile

thefile.__enter__
thefile.__exit__

finally __exit__
try..finally

PEP 343

try..except try..finally

120

Python

1. Raise


2. Python Handler


3. Raising Exceptions

121

Python Python Standrad Library


Python Python

Python
Library Reference


Python

sys

sys sys.argv

Python sys

>>> import sys


>>> sys.version_info
sys.version_info(major=3, minor=5, micro=1, releaselevel='final', serial=0)
>>> sys.version_info.major == 3
True

sys version_info

Debugging

logging

stdlib_logging.py

122

import os
import platform
import logging

if platform.platform().startswith('Windows'):
logging_file = os.path.join(os.getenv('HOMEDRIVE'),
os.getenv('HOMEPATH'),
'test.log')
else:
logging_file = os.path.join(os.getenv('HOME'),
'test.log')

print("Logging to", logging_file)

logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s : %(levelname)s : %(message)s',
filename=logging_file,
filemode='w',
)

logging.debug("Start of the program")


logging.info("Doing something")
logging.warning("Dying now")

$ python stdlib_logging.py
Logging to /Users/swa/test.log

$ cat /Users/swa/test.log
2014-03-29 09:27:36,660 : DEBUG : Start of the program
2014-03-29 09:27:36,660 : INFO : Doing something
2014-03-29 09:27:36,660 : WARNING : Dying now

cat test.log

os platform
logging Log

platform.platform()
import platform; help(platform) Windows
Home DriveHome Folder

123

os.path.join()

logging

Debugging
Regular Expressions

Doug Hellmann Python Module of the


Week Python

Python
Python

Python Python

124

Python
Python

>>> def get_error_details():


... return (2, 'details')
...
>>> errnum, errstr = get_error_details()
>>> errnum
2
>>> errstr
'details'

a, b = <some expression>

Python

>>> a = 5; b = 8
>>> a, b
(5, 8)
>>> a, b = b, a
>>> a, b
(8, 5)

__init__ __del__

x[key]

__getitem__() Python

list

125

__init__(self, ...)


__del__(self)


__str__(self)

print str()
__lt__(self, other)

<+>

__getitem__(self, key)

x[key]
__len__(self)

len()

>>> flag = True


>>> if flag: print('Yes')
...
Yes

Lambda
lambda lambda

more_lambda.py

126

points = [{'x': 2, 'y': 3},


{'x': 4, 'y': 1}]
points.sort(key=lambda i: i['y'])
print(points)

$ python more_lambda.py
[{'y': 1, 'x': 4}, {'y': 3, 'x': 2}]

list sort key

def
Lambda

List Comprehension
2
2

more_list_comprehension.py

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)

$ python more_list_comprehension.py
[6, 8]

if i > 2 2*i

Boilerplate

127

* **

>>> def powersum(power, *args):


... '''Return the sum of each argument raised to the specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100

args *
args **

assert

assert Assert

assert
AssertionError

>>> mylist = ['item']


>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> assert len(mylist) >= 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError

assert

128

Decorators
retry
5

from time import sleep


from functools import wraps
import logging
logging.basicConfig()
log = logging.getLogger("retry")

def retry(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
MAX_ATTEMPTS = 5
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return f(*args, **kwargs)
except:
log.exception("Attempt %s/%s failed : %s",
attempt,
MAX_ATTEMPTS,
(args, kwargs))
sleep(10 * attempt)
log.critical("All %s attempts failed : %s",
MAX_ATTEMPTS,
(args, kwargs))
return wrapped_f

counter = 0

@retry
def save_to_database(arg):
print("Write to a database or make a network call or etc.")
print("This will be automatically retried if exception is thrown.")
global counter
counter += 1
#
#
if counter < 2:
raise ValueError(arg)

if __name__ == '__main__':
save_to_database("Some bad value")

129

$ python more_decorator.py
Write to a database or make a network call or etc.
This will be automatically retried if exception is thrown.
ERROR:retry:Attempt 1/5 failed : (('Some bad value',), {})
Traceback (most recent call last):
File "more_decorator.py", line 14, in wrapped_f
return f(*args, **kwargs)
File "more_decorator.py", line 39, in save_to_database
raise ValueError(arg)
ValueError: Some bad value
Write to a database or make a network call or etc.
This will be automatically retried if exception is thrown.

http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
http://toumorokoshi.github.io/dry-principles-through-python-decorators.html

Python 2 Python 3

"Six" library
Porting to Python 3 Redux by Armin
Python 3 experience by PyDanny
Official Django Guide to Porting to Python 3
Discussion on What are the advantages to python 3.x?

Python Python

Python

130

Python Python
Python

Python
;-)

https://github.com/thekarangoel/Projects#numbers ( Martyr2
)

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills


Intermediate Python Projects

131

Python Cookbook Python



Python Module of the Week

The Hitchhiker's Guide to Python!


The Elements of Python Style
Python Big Picture
"Writing Idiomatic Python" ebook

Full Stack Web Development with Flask


PyVideo

Official Python Dos and Don'ts


Official Python FAQ
Norvig's list of Infrequently Asked Questions
Python Interview Q & A
StackOverflow questions tagged with python

Hidden features of Python


What's the one code snippet/python trick/etc did you wish you knew when you learned
python?
Awaretek's comprehensive list of Python tutorials

Python python-tutor list

132

Python Official Python Planet

Python

pip

Flask

Flask Official Quickstart


The Flask Mega-Tutorial
Example Flask Projects

Python GUIGraphical
User Interface Python Python
C C++

Python GUI

Kivy

http://kivy.org
PyGTK

GTK+ Python GNOME GTK+


GUI Glade
GTK+ GNU/Linux
Windows GTK+
PyGTK
PyQt

133

Qt Python KDE Qt Designer


Qt Qt
GPL PyQt
Qt 4.5 GPL
PySide
wxPython

wxWidgets Python wxPython


GNU/LinuxWindwosMac
IDE wxPython GUI SPE
(Stani's Python Editor) wxGlade GUI wxPython
wxPython

GUI
GuiProgramming wiki page at the official python website

Python GUI
GUI
Windwos Mac GNU/Linux
GNU/Linux KDE GNOME

'The Python Papers, Volume 3, Issue 1' (PDF) 26

CPython CPython C
Classical Python

Python

Jython

Java Python Python Java



IronPython

.NET Python Python .NET


134

PyPy

Python Pyhon
C
JavaC#

CLPython Common Lisp Python Brython


JavaScript Python JavaScript Web
Ajax

Functional Programming Howto by A.M. Kuchling


Functional programming chapter in 'Dive Into Python' book
Functional Programming with Python presentation
Funcy library
PyToolz library

Python Python

1.

2.

pickle

135
FLOSS

FLOSS
2003 :-)

/ FLOSS
FLOSS

FLOSS Python
Python

FLOSS

Linux FLOSS GNU/Linux Linux


Linus Torvalds Android Linux
Linux

Ubuntu Canonical Linux


GNU/Linux FLOSS
CD GNU/Linux
Ubuntu

LibreOffice
MS Word MS PowerPoint

Mozilla Firefox

Mono .NET GNU/LinuxWindows


FreeBSDMacOS .NET

Apache Web Web


Web Apache
Microsoft IIS

VLC DivX MP3 Ogg VCD DVD


;-)

FLOSS
Perl PHP Drupal PostgreSQL
TORCS KDevelop IDEXine VIM Quanta+

136
FLOSS

Banshee GIMP

FLOSS

OMG! Ubuntu!
Web Upd8
DistroWatch
Planet Debian

FLOSS

GitHub Explore
Code Triage
SourceForge
FreshMeat

FLOSS

137

FLOSS

Red Hat 9.0 Linux


Fedora Core 3 Linux

KWord

DocBook XML Kate


OpenOffice PDF
HTML

XEmacs DocBook XML

Quanta+ Fedora Core 3 Linux


XSL CSS HTML
Python

MediaWiki
Wiki

VimPandoc Mac OS X

AsciiDoc Emacs 24.3 tomorrow Fira Mono


adoc-mode

2016 AsciiDoctor C/C++ ++


Asciidoc

138

Markdown GitBook Spacemacs


editor

http://www.swaroopch.com/about/

139

Python Diamond
Qt Python Perl
Eric S. Raymond
Python
Perl-Qt PyQt Python

Python O'Reilly
Python
Python

Python Red Hat 9.0 Linux


KWord Python
30
Python

Python
:)

4.0
2016 1 19
Python 3
Markdown GitBook Spacemacs
3.0

140

2014 3 31
Python 2 AsciiDoc adoc-mode
2.0

2012 10 20
Pandoc MediaWiki

nonlocal
1.90

2008 9 4
3.5
Python 3.0
MediaWiki
1.20

2005 1 13
Fedora Core 3 Quanta+
DocBook
1.15

2004 3 28

1.12

2004 3 16

1.10

2004 3 9

1.00

2004 3 8

0.99

2004 2 22

0.98

2004 2 16
Python CSS XHTML
VIM

141

0.97

20014 2 13
DocBook XML

0.93

2004 1 25
IDLE Windows
0.92

2004 1 5

0.91

2003 12 30

0.90

2003 12 18
OpenOffice
0.60

2003 11 21

0.20

2003 11 20

0.15

2003 11 20
DocBook XML XEmacs
0.10

2003 11 14
KWord

142

Ashraf Ali Khalaf


http://www.khaledhosny.org/byte-of-python/index.html
sourceforge.net
http://itwadi.com/byteofpython_arabi

Jahangir Shabiyev (c.shabiev@gmail.com)


https://www.gitbook.com/book/jahangir-sh/piton-sancmasi

Samuel Dias Neto (samuel.arataca@gmail.com)


Python 2.3.5

Rodrigo Amaral (rodrigoamaral@gmail.com)

Moises Gomez (moisesgomezgiron@gmail.com)

143

Moiss Gmez -

Python Swaroop

BoP

2005 1.20 BoP


Juan Shen orion_val@163.com
BoP
Python

2017 i@molun.net 4.0 GitHub


Gitbook

2017 https://bop.molun.net

Fred Lin (gasolin@gmail.com)

http://code.google.com/p/zhpy/wiki/ByteOfZhpy

Python
Python

144

Fred Lin - Delta Network


TurboGears

Python (:-p) Python


Python Python
Python

Python
zhpyPython in Chinese 8 7

zhpyZ.H.? zippy Python Python


Gregory (coulix@ozforces.com.au)

Grard Labadie (gerard.labadie@gmail.com)

Lutz Horn (lutz.horn@gmx.de) Bernd Hengelein (bernd.hengelein@gmail.com)


Christoph Zwerschke (cito@online.de)

http://ftp.jaist.ac.jp/pub//sourceforge/a/ab/abop-german.berlios/

Lutz Horn

145

32

Java Python
Python GUI
Web Struts
Java Python
Ruby
Python Ruby
Java
How to Think Like a
Computer Scientist: Learning with PythonDive into Python
Python

DocBook

Bernd Hengelein

Lutz

34 1980 20 Commodore
64
C++

Python
Python
Python

Lutz Lutz

Ubuntu Python
@savvasradevic

Daniel (daniel.mirror@gmail.com) http://python.or.id/moin.cgi/ByteofPython

146

Wisnu Priyambodo (cibermen@gmail.com)

Bagus Aji Santoso (baguzzzaji@gmail.com)

Enrico Morelli (mr.mlucci@gmail.com) Massimo Lucci (morelli@cerm.unifi.it)

http://www.gentoo.it/Programmazione/byteofpython

Massimo Lucci and Enrico Morelli -


MassimoEnrico CED
/ Python
Linux Gentoo/Linux
www.gentoo.it
www.nmr.it
Python

Calvina Bice http://besthcgdropswebsite.com/translate/a-


byte-of-python/

Shunro Dozono (dozono@gmail.com)

Jeongbin Park (pjb7687@gmail.com)


https://github.com/pjb7687/byte_of_python

147

Jeongbin Park

Python
Python

Python
Python

Ariunsanaa Tunjin (luftballons2010@gmail.com)

2009 11 9 Ariunsanaa

Eirik Vgeskar Sandvika videregende skole

Eirik Vgeskar:


Python
Python


Dominik Kozaczko (dominik@kozaczko.info)


Uk Pythona

2009 10 2 Dominik

Dominik Kozaczko -

148

Fidel Viegas (fidel.viegas@gmail.com)

Paul-Sebastian Manole (brokenthorn@gmail.com)

Paul-Sebastian Manole - Spiru Haret


Python
Python
Python
Swaroop

Vladimir Smolyar (v_2e@ukr.net) http://wombat.org.ua/AByteOfPython/

Averkiev Andrey (averkiyev@ukr.net)

"BugSpice" (amortizerka@gmail.com)

http://forum.ubuntu-rs.org/Thread-zagrljaj-pitona

Albertio Ward (albertioward@gmail.com)


http://www.fatcow.com/edu/python-swaroopch-sl/

149

Translation for education


Slavonic




Alfonso de la Guarda Reyes (alfonsodg@ictechperu.net) Gustavo Echeverria


(gustavo.echeverria@gmail.com) David Crespo Arroyo (davidcrespoarroyo@hotmail.com)
Cristian Bermudez Serna (crisbermud@hotmail.com)

Gustavo Echeverria

C# .Net
Python Ruby Python
Python
Maximiliano
Soler A Byte of Python

Cristian Bermudez Serna

Python

Mikael Jacobsson (leochingkwake@gmail.com)

Trker SEZER (tsezer@btturk.net) Bugra Cakir (bugracakir@gmail.com)

"Where is Turkish version? Bitse de okusak."

150

1. https://github.com/swaroopch/byte-of-python
2. Fork
3. Git
4. GitBook Markdown
5. .md
6. GitBook.com
PDFEPUB

151



PDF/EPUB

152

También podría gustarte