Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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
-- Biologist John
Python
Pythonistas Python -- Mangesh
Python Swaroop
-- Apostolos
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
N800 Python
Python Python --
Jason Delport
Python
Python -- Justin LoveTrue
Python:) Chinmay
Python
-- Patrick Harrington
Python
:) --
Gadadhari Bheem
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
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
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
11 Byte of Python
Python Python 2 Python 3
print 'hello world' Python 3
Python
Python 2 3
Python
12
Nakagawa KanonZxteloivYukko
SwaroopC
Hblog@swaroopch.com
i@molun.net
Python
201712
2017 1 9 2 16 Haruki
KirigayaYuki KiriyamaNakagawa Kanon
Cloud yurikaka
aristotll Tian
Zhao 4.02c
13
2017 5 1 Nangcr
Haruki KirigayaYuki Kiriyamashuven
4.04c
14
Python
Python
Python
Python
Python
Python
Python
Python Python
Python
Python Python
15
Python
Python FLOSS /
FLOSS Python
Python
Python
Python
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
Python 3 VS Python 2
Python 2Python 3
Python 3
Python
Python
Pyhon 2 Python 3
Python 2 Python 3
17
Python
ESR Python
18
Windows
https://www.python.org/downloads/ Python
Python 3.5.1 Windows
Python
Path
Windows Python
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
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
Python 3.5.1
21
Python
Terminal
python3 [enter] Python Python Prompt
Python
print("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
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
Pure Python
24
untitled helloworld
Create
hello
25
print("hello world")
Run 'hello'
26
Vim
1. Vim
Mac OS X HomeBrew macvim
Windows Vim
27
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.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 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
print('hello world')
2
Literal Constants 5 1.23
This is a string
31
3
2
IntegersFloats
long int
Python
""
"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
format
format
age = 20
name = 'Swaroop'
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
a b c
'
"What's your name?" 'What's your name?'
Python
Escape Sequence
\ 'What\'s your
name?'
\n
\t
35
4
r R Raw
Backwhacking
'\\1' r'\1'
Veriables
Identifiers
36
Data Type
Classes
Python Object
objectsomething
Python Strongly
Python
Python
PyCharm
1. PyCharm
2.
3.
4.
37
1.
2.
3.
4. python program.py
# var.py
i = 5
print(i)
i = i + 1
print(i)
38
5
6
This is a multi-line string.
This is the second line.
= 5
i Statement
i 5 print
i
1 i
6
print('hello world')
Python Python
( ; )
i = 5
print(i)
i = 5;
print(i);
39
i = 5; print(i);
i = 5; print(i)
Python
s = 'This is a string. \
This continues the string.'
print(s)
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)
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
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 = 2; y = 3; x != y True
5
not
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, <, <=, >, >=, !=, ==
&
<<, >>
+, -
*, /, //, %
+x, -x, ~x
**
46
(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
$ python expression.py
Area is 10
Perimeter is 14
47
LengthBreadth
AreaPerimeter length *
breadth area print
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
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')
print('Done') Python
C/C++
C/C++
while
while while
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
while
running True while
else
while else
break
53
C/C++
while else
for
for...in Iterates
Sequences
for.py
$ 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
else for
break
for...in
range
C/C++/Java/C#
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
57
Functions
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
#
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
say('Hello')
say('World', 5)
$ python function_default.py
Hello
WorldWorldWorldWorldWorld
say
times 1
say
say 5 Say
Keyword Arguments
`function_keyword.py
62
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
#
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
print(maximum(2, 3))
$ python function_return.py
3
64
maximum
if...else
def some_function():
pass
Python pass
max
DocStrings
Python Documentation Strings
docstringsDocStrings
function_docstring.py
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.
DocString
ModulesClass
__doc__
print_max Python
Class
Python help()
__doc__
help(print_max) q
help
Python
Python
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
68
Python Python
sys.path
sys
argv
sys.argv List
IDE
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
from..import
argv sys.
from sys import argv
from...import import
__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
.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
say_hi()
print('Version', __version__)
mymodule_demo2.py mymodule_demo.py
mymodule __version__
import
say_hi __version__
Python
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
vars()
73
Packages
__init__.py Python
Python
world asiaafrica
indiamadagascar
Python
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
$ 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
help(list)
Tuple
ds_using_tuple.py
#
#
#
#
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))
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
dict
ds_using_dict.py
# abAddressBook
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
#
del ab['Spammer']
#
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
ab
del
del
item
for...in name
address for
Guido
in
dict help(dict)
Symbol Table
Sequence
81
Slicing
ds_seq.py
# 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
2 024 3
03
Python
SetCollection
84
Refer
Binding
ds_reference.py
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist
mylist = shoplist
#
del shoplist[0]
$ 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
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
#
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
source .
os.system
zipfile os.system
Phases
1. What/
2. How/
3. Do It/
4. Test/
5. Use/
6. Maintain/
97
Python
Python
1. Verbosity
98
Procedure-oriented
Class
TypeObjectInstance
int int
help(int)
Field
Method
Attribute
class
self
Python
self
self
99
C++/Java/C#
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
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
#
#
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()
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.
population
Robot name self
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
Python
C++/Java/C#
Python
Vireual
Reuse
InheritanceType and Subtype
SchoolMember
Inherit
105
SchoolMember
SchoolMember
ID
SchoolMember
Polymorphism
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))
#
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)
6
__init__ self
Teacher Student
__init__ Python SchoolMember
__init__ Python
self
Inheritance Tuple
Multiple Inheritance
print \n
Python
108
Python
type
2.
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)
$ 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()
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
$ 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"
Unicode UTF-8
open
# encoding=utf-8
import io
import
Unicode Python
UTF-8 # encoding=urf-8
4
114
"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
NameError Python
2
Error Handler
Try [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
Python
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
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
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
Library Reference
Python
sys
sys sys.argv
Python sys
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')
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s : %(levelname)s : %(message)s',
filename=logging_file,
filemode='w',
)
$ 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
Python
Python
Python Python
124
Python
Python
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()
Lambda
lambda lambda
more_lambda.py
126
$ python more_lambda.py
[{'y': 1, 'x': 4}, {'y': 3, 'x': 2}]
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
* **
args *
args **
assert
assert Assert
assert
AssertionError
assert
128
Decorators
retry
5
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
)
131
132
Python
pip
Flask
Python GUIGraphical
User Interface Python Python
C C++
Python GUI
Kivy
http://kivy.org
PyGTK
133
GUI
GuiProgramming wiki page at the official python website
Python GUI
GUI
Windwos Mac GNU/Linux
GNU/Linux KDE GNOME
CPython CPython C
Classical Python
Python
Jython
134
PyPy
Python Pyhon
C
JavaC#
Python Python
1.
2.
pickle
135
FLOSS
FLOSS
2003 :-)
/ FLOSS
FLOSS
FLOSS Python
Python
FLOSS
LibreOffice
MS Word MS PowerPoint
Mozilla Firefox
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
KWord
MediaWiki
Wiki
VimPandoc Mac OS X
138
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
:)
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
143
Moiss Gmez -
Python Swaroop
BoP
2017 https://bop.molun.net
http://code.google.com/p/zhpy/wiki/ByteOfZhpy
Python
Python
144
Python
zhpyPython in Chinese 8 7
Gregory (coulix@ozforces.com.au)
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
146
http://www.gentoo.it/Programmazione/byteofpython
147
Jeongbin Park
Python
Python
Python
Python
2009 11 9 Ariunsanaa
Eirik Vgeskar:
Python
Python
2009 10 2 Dominik
Dominik Kozaczko -
148
"BugSpice" (amortizerka@gmail.com)
http://forum.ubuntu-rs.org/Thread-zagrljaj-pitona
149
Gustavo Echeverria
C# .Net
Python Ruby Python
Python
Maximiliano
Soler A Byte of Python
Python
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