Professional Documents
Culture Documents
A Byte of Python
A Byte of Python
Articles
Python el: 1
Python el: 2
Python el: 3
Python el: 6
Python el: 10
Python el: 12
Python el: 17
Python el: 25
Python el: 30
Python el: 37
Python el: 47
Python el: 54
Python el: 65
Python el: 74
Python el: 83
Python el: 87
Python el: 92
Python el: 97
Python el: 102
Python el: 107
Python el: 111
Python el: 113
Python el: 114
References
Article Sources and Contributors 116
Article Licenses
License 117
Python el: 1
Python el:
( )
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18. ;
19. :
20. :
21. :
22. :
Python el: 2
Python el:
, , :
,
,
... !
Translations (
).
[1]
Ubuntu ,
online .
References
[1] http:/ / ubuntu-gr. org
Python el: 3
Python el:
Python
. , ' :
Python.
. "A
Byte of Python" " ",
"" .
Python.
, .
Python,
. ,
Python .
, Python
.
. : ,
Python!
Python
'Diamond' .
Python Perl Qt.
[1] Eric S. Raymond, hacker,
Python . PyQt
Perl-Qt. , Python .
Python,
! O'Reilly ,
. , Python. ,
. Python
. ,
.
Python, ()
Red Hat 9.0 Linux KWord. ,
Python. ,
30 . , ,
. , '
Python. ,
.
Python,
, .
, ,
, .
Python el: 4
2005
Python 3.0 ( 2008). Python 3.0
, ,
. , " ,
", Python 3000
.
, .
[2] .
'
"" .
' .
http:/ / www. swaroopch. com/ notes/ Python
, ,
[3] ( ), .
1. Creative Commons Attribution-Noncommercial-Share Alike 3.0
Unported [4].
:
.. ,
..
:
.
(
).
. , ,
/ .
,
.
.
.
2. http://www.swaroopch.com/
notes/Python
.
3. / ' 3-clause BSD License [5]
.
4. '
.
Python el: 5
. , ,
, ' , .
.
,
[3] .
:
,
.
-- C. A. R. Hoare
.
-- C. W. Wendte
References
[1] http:/ / pythonology. org/ success& story=esr
[2] http:/ / www. swaroopch. com/ contact/
[3] http:/ / www. swaroopch. com/ buybook
[4] http:/ / creativecommons. org/ licenses/ by-nc-sa/ 3. 0/
[5] http:/ / www. opensource. org/ licenses/ bsd-license. php
Python el: 6
Python el:
Python .
.
Python :
Python , .
. Python ,
( ) ,
.
.
Guido van Rossum, Python, "Monty
Python's Flying Circus" BBC.
.
Python
Python . Python
, ! Python
.
.
, Python. Python
, .
Python ( ).
, ,
, ' .
.
Python -
Python.
Python,
, ..
, Python ( )
. Python
Python el: 7
.
Python Linux, Windows, FreeBSD, Macintosh,
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 !
.
C C++
, C C++
( 0 1)
. ,
.
Python, , . '
. , Python
bytecode .
, Python
, , .,
.. Python ,
Python !
Python (procedure-oriented)
(object-oriented). ,
. ,
.
Python ,
C++ Java.
, C
C++ Python .
Python C/C++
'scripting' .
Python .
, , ,
, , , CGI, FTP, email, XML, XML-RPC, HTML,
WAV, , (GUI -graphical user interfaces), Tk,
.
Python. 'Batteries Included' Python.
,
wxPython [1] , Twisted [2], Python Imaging Library [3] .
Python el: 8
Python .
Python .
Perl;
, Perl , , ,
.
Perl,
! , Perl ,
hacks " ". ,
,
Perl Yahoo!
Perl, Python , ,
. Perl
Python . Perl
hacks , ( ) hack. ,
Perl 6 ' .
Perl, CPAN
[4]
- Comprehensive Perl Archive Network. ,
Perl
- ' .
Perl Python
Python.
Python [5].
Ruby;
, Ruby , ,
.
Ruby ,
.
Python Ruby, Python, .
Ruby,
. , .
hackers ESR Python:
Eric S. Raymond " "
. Python [6]
( ).
Python.
Bruce Eckel Thinking in Java Thinking in C++.
Python. Python
.
Python el: 9
[7] ( ) .
Peter Norvig Lisp
Google ( Guido van Rossum ). Python
Google. Google Jobs [8]
Python .
Python 3.0
Python 3.0 . Python 3000 Py3K.
Python
, .
Python 2.x,
2.x 3.x [9] ( ).
( ):
Guido van Rossum [10]
Python 2.6 [11] (
Python 2.x Python 3.0)
Python 3.0 [12]
Python 2.6 3.0 [13]
Python 3000 ( ) [14]
Python 3.0 [15]
Python ( ) [16]
References
[1] http:/ / www. wxpython. org
[2] http:/ / www. twistedmatrix. com/ products/ twisted
[3] http:/ / www. pythonware. com/ products/ pil/ index. htm
[4] http:/ / cpan. perl. org
[5] http:/ / pypi. python. org/ pypi
[6] http:/ / www. linuxjournal. com/ article. php?sid=3882
[7] http:/ / www. artima. com/ intv/ aboutme. html
[8] http:/ / www. google. com/ jobs/ index. html
[9] http:/ / docs. python. org/ 3. 0/ library/ 2to3. html
[10] http:/ / www. artima. com/ weblogs/ viewpost. jsp?thread=208549
[11] http:/ / docs. python. org/ dev/ whatsnew/ 2. 6. html
[12] http:/ / docs. python. org/ 3. 0/ whatsnew/ 3. 0. html
[13] http:/ / www. python. org/ dev/ peps/ pep-0361/
[14] http:/ / www. python. org/ dev/ peps/ pep-3000/
[15] http:/ / www. python. org/ dev/ peps/ pep-3100/
[16] http:/ / www. python. org/ download/ releases/ 3. 0/ NEWS. txt
Python el: 10
Python el:
Python 2.x ,
Python 3.0. .
Linux BSD
Linux Ubuntu, Fedora, OpenSUSE {
}, BSD FreeBSD, Python
.
Python Linux ,
( konsole gnome-terminal) python -V
.
$ python -V
Python 3.0b1
$ prompt , .
, prompt
$.
, Python
.
, :
$ python -V
bash: Python: command not found
Python. .
Python 2.x, python3 -V.
' , Python 3.x .
Python [1] .
.
, apt-get Ubuntu/Debian
Linux Debian, yum Fedora Linux, pkg_add FreeBSD, ..
. ,
,
.
Python el: 11
Windows
http:/ / www. python. org/ download/ releases/ 3. 1/
, 3.1 32 bit [2] 3.1 64 bit [3] .
13 MB
. Windows.
"" ,
! , IDLE.
Python
Windows. , Linux
Python .
DOS Prompt
Python Windows .. DOS
prompt, PATH .
Windows 2000, XP, 2003, Control Panel -> System -> Advanced ->
Environment Variables. PATH 'System Variables',
Edit ;C:\Python30 , . ,
, Python.
Windows, C:\AUTOEXEC.BAT :
'PATH=%PATH%;C:\Python30' ( ) . Windows NT,
AUTOEXEC.NT.
Mac OS X
Mac OS X Python .
Terminal.app python -V
Linux.
Linux, Python .
,
. Windows, Python
. , Python
.
, Python.
Python el: 12
References
[1] http:/ / www. python. org/ download/ releases/ 3. 0/
[2] http:/ / www. python. org/ ftp/ python/ 3. 1/ python-3. 1. msi
[3] http:/ / www. python. org/ ftp/ python/ 3. 1/ python-3. 1. amd64. msi
Python el:
", !" (Hello, World!)
Python. , Python.
Python :
(interactive interpreter prompt)
(source code file).
.
(interpreter) python3 .
Windows,
PATH .
IDLE, Start Programs Python 3.1 IDLE (Python GUI).
print(', !') Enter.
Hello World .
Python (output) !
(statement) Python. print ()
. , , ! .
, ctrl-d ( EOF - End Of File) IDLE
Linux/BSD. Windows, ctrl-z
Enter.
Python el: 13
(Editor)
Python ,
.
.
. Python ,
(
) .
Python o
. ,
.
Windows, IDLE. IDLE
IDLE . : Notepad -
, .
IDLE ( VIM ) .
Linux/FreeBSD, .
, Geany [1].
Python
.
, , Gedit Kate,
Linux GNOME KDE,
.
, .
.
, Vim Emacs.
Python . Vim
. Vim
Emacs,
.
, IDLE, IDE (Integrated Development Environment -
) . IDLE
Python Windows OS X.
Linux [2] BSD (repositories).
IDLE . ,
IDLE [3].
' ,
Python [4] . IDE
( ) Python. IDE
Python [5] . Python,
.
Python el: 14
, Python -
Python .
Vim
Vim Python IDE John M.
Anderson [6].
Emacs
Emacs Python IDE Ryan
McGuire [7].
.
, Hello, World!
(, !) - , ! .
Simon Cozens [8] ,
:) .
,
helloworld.py
IDLE, File New Window .
File Save.
#!/usr/bin/python3
#Filename: helloworld.py
print(', !')
( Linux DOS)
python3 helloworld.py.
helloworld.py
helloworld.py.
IDLE, Run Run Module
F5.
:
$ python3 helloworld.py
, !
, !
Python.
,
. Python - ..
print Print - p P
. , (tabs)
() - .
Python el: 15
. -
# .
.
Python ' , .
shebang -
#! , Linux/Unix
.
.
'
python3 helloworld.py .
-
. ,
!
Python. (function) print
', !'.
-
. , ', !'
(string) - ,
.
Python
Linux/Unix Windows
. ,
chmod .
#!/usr/bin/env python3
env Python .
Python el: 16
, '
. ;
PATH.
,
PATH , , .
PATH.
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
$ cp helloworld.py /usr/local/bin/helloworld
$ helloworld
, !
PATH . '
' , ..
sudo, : sudo cp helloworld.py /usr/local/bin/helloworld
( '
).
PATH echo ( )
$
. PATH
PATH=$PATH:/home/swaroop/mydir '/home/swaroop/mydir'
.
$PATH PATH=$PATH:/home/swaroop/mydir
, .
$PATH.
scripts
, . .. cd
Linux DOS.
Python , script .
Python,
help.
. , help(print) -
print .
q .
, Python.
help() help!
(operators) return,
.. help('return') Python
Python el: 17
, Python .
Python, Python.
:
[1] http:/ / www. geany. org/
[2] http:/ / love-python. blogspot. com/ 2008/ 03/ install-idle-in-linux. html
[3] http:/ / www. python. org/ idle/ doc/ idlemain. html
[4] http:/ / www. python. org/ cgi-bin/ moinmoin/ PythonEditors
[5] http:/ / www. python. org/ cgi-bin/ moinmoin/ IntegratedDevelopmentEnvironments
[6] http:/ / blog. sontek. net/ 2008/ 05/ 11/ python-with-a-modular-ide-vim/
[7] http:/ / www. enigmacurry. com/ 2008/ 05/ 09/ emacs-as-a-powerful-python-ide/
[8] "Beginning Perl"
Python el:
, ! , ; -
, .
Python .
(Literal Constants)
5, 1.23, 9.25e-3
' ' " !".
- . 2 -
. , .
Python : (integers), (floating
point) (complex numbers).
2 .
( floats ) 3.23 52.3E-4.
E 10. , 52.3E-4 52.3 * 10-4.
(-5+4j) (2.3 - 4.6j)
'long int' . .
Python el: 18
(Strings)
. .
Unicode,
[1].
"ASCII-only" , Unicode ASCII.
ASCII-encoded byte-stream, str.encode("ascii").
, Stack Overflow [2].
, Unicode.
Python
, ' Python.
, '
'. , . (Whitespace) (Tabs),
.
.
" ;"
- (""" ''').
. :
''' . .
.
" ;" .
: '. .'
'''
(Escape Sequences)
('), ;
, ' !. ' ' !'
Python . ',
.
. \' -
. , ' \' !'.
.. " ' !",
. ,
. ,
\\.
;
, - \n .
\n .
Python el: 19
(Tab) \t.
.
,
, .
:
" .\
."
" . .".
(Raw Strings)
, ..
, (raw) r R . '
: r"Newlines are indicated by \n". ' ,
, \n
.
(Immutable)
, .
, .
.
(Concatenation)
, Python.
, 'What\'s ' 'your name?' "What's your
name?".
C/C++
char Python. '
.
Perl/PHP
- .
(Regular Expression)
.
. ,
'\\1' r'\1'.
format
.
format().
. '
(.) , .
, format .
Python el: 20
#!/usr/bin/python3
# Filename: str_format.py
age = 25
name = ''
$ python str_format.py
25 .
;
:
(specifications) ,
format (arguments)
format.
{0} name
. , {1} age
.
: ' ' + name + ' ' +
str(age) + ' .', . ,
format .
, format, ,
, .
H Python format .
:
(Variables)
-
. .
- ,
. /
. , (method)
Python el: 21
, .
.
.
:
( ASCII
ASCII Unicode) ('_').
( ASCII
ASCII Unicode ), ('_') (0-9).
(case-sensitive). ,
myname myName . n
N .
: i, __my_name, name_23, a1b2_c3
random_utf8_characters_.
: 2things, this is spaced out,
my-name, "this_is_in_quotes".
, .. , __.
.
, . ,
.
, Python o ,
. ' ', ' '.
Python
, .
.
.
Python
Python
:
1. .
2. .
3. .
Python .py.
4. python var.py IDLE
. .
Python el: 22
:
# Filename : var.py
i = 5
print(i)
i = i + 1
print(i)
$ python var.py
5
6
This is a multi-line string.
This is the second line.
:
. , 5
i (=). (statement)
, i 5. ,
i print , ,
.
1 i .
, 6.
, s .
.
/ (declaration) (data type
definition).
.
Python . Python
.
print('Hello World') -
( ),
.
, Python
.
,
(semicolon) (;)
/. ,
Python el: 23
i = 5
print(i)
i = 5;
print(i);
i = 5; print(i);
i = 5; print(i)
,
. ,
. , ,
. , ,
Python.
.
explicit line joining.
s = 'This is a string. \
This continues the string.'
print(s)
print\
(i)
print(i)
,
. (), [] {}.
implicit line joining.
.
Python el: 24
(Indentation)
Python. ,
. . ( )
,
.
.
, (block).
.
. :
i = 5
print(' ', i) # !
print(', ', i)
, :
. Python
, , .
(
, ).
, .
. (1 tab)
(4 spaces) .
.
, .
Python (braces). from __future__
import braces .
Python el: 25
,
. .
References
[1] http:/ / www. unicode. org/ faq/ basic_q. html#16
[2] http:/ / stackoverflow. com/ questions/ 175240/ how-do-i-convert-a-files-format-from-unicode-to-ascii-using-python#175270
[3] http:/ / www. python. org/ dev/ peps/ pep-3101/
Python el:
(expressions).
2 + 3. (operators) (operands).
+
-.
. , 2 3.
:
. , 2 + 3,
Python:
>>> 2 + 3
5
>>> 3 * 5
15
>>>
- , -5.2 . 50 - 24
. 26.
* 2 * 3 6. 'la' * 3 'lalala'.
(string)
.
** x y. 3 ** 4 81 ( 3 * 3 * 3 * 3).
/ x y. 4 / 3 1.3333333333333333.
Python el: 26
// ( 4 // 3 1.
) .
(Floor
Division)
& . 5 & 3 1.
| . 5 | 3 7.
^ . 5 ^ 3 6.
~ x ~5 -6.
-(x+1).
== . 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.
.
, '
:
:
a = 2; a = a * 3
a = 2; a *= 3
=
= .
( )
2 + 3 * 4. , ;
.
.
Python,
. , Python
.
, Python [1],
.
. .
.
lambda Lambda
or
and
not x
in, not in
is, is not
&
<<, >>
+, -
*, /, //, % , , ,
Python el: 28
+x, -x ,
~x
**
x.attribute
x[index] Subscription
x[index1:index2] (Slicing)
f(arguments ...)
(expressions, ...)
[expressions, ...]
{key:datum, ...}
.
. ,
+ - .
, .
, 2 + (3 * 4) 2 + 3 * 4
. ,
( ) ( .. 2 + (3 + 4)).
- .
, ,
(2 + 3) * 4.
(Associativity)
. , 2 + 3 + 4
(2 + 3) + 4.
. a = b = c a = (b = c).
(Expressions)
:
#!/usr/bin/python
# Filename: expression.py
length = 5
breadth = 2
:
Python el: 29
$ python expression.py
Area is 10
Perimeter is 14
:
(length) (breadth) .
. length * breadth
(variable) area print. ,
' 2 * (length + breadth) print.
, Python " " . '
'Area is' area, Python
(
). Python .
, -
. ,
.
References
[1] http:/ / docs. python. org/ 3. 0/ reference/ expressions. html#evaluation-order
Python el: 30
Python el:
, ,
Python . ; , ,
,
.. , ;
, .
Python - if, for while.
if
if (if) ,
( if-block), (else)
( else-block). else .
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: if.py
number = 23
guess = int(input(' : '))
if guess == number:
print(', .') # (block)
print('( !)') #
elif guess < number:
print(', .') #
# ...
else:
print(', .')
# guess > number
print('')
#
if
$ python if.py
: 50
, .
Python el: 31
$ python if.py
: 22
, .
$ python if.py
: 23
, .
( !)
:
. number , .. 23.
input().
. ' .
(string) input,
.
enter, input() .
, int
guess. , int ,
'
( ).
. ,
.
Python . ' , Python.
. ;
if Python
.
, ,
' .
elif if else-if else
if-elif-else.
.
elif else ,
( , ).
if if (if-block) if ..
if.
elif else . if :
if True:
print(', ')
Python if
elif else,
if.
print(''). ' Python
Python el: 32
.
,
' . (
C/C++) , '
.
C/C++
switch Python.
if..elif..else (
).
while
while ,
. while ( looping
statement). while else.
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: while.py
number = 23
running = True
while running:
guess = int(input(' : '))
if guess == number:
print(', .')
running = False # while
elif guess < number:
print(', .')
else:
print(', .')
else:
print(' while .')
#
print('')
$ python while.py
: 50
, .
: 22
,
: 23
, .
Python el: 33
while .
:
' ,
- .
, .
while.
input if while running
True while. running True
while (while-block).
, , . running.
true (), while (while-block),
else (else-block)
.
else while False () -
.
else while, , break.
True () False () (Boolean types)
1 0 .
C/C++
else while.
for
for..in , ,
. .
.
.
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: for.py
$ python for.py
1
2
3
4
loop
Python el: 34
:
' .
range.
range ,
. , range(1,5)
[1, 2, 3, 4]. , range (step count) 1.
range, (step count).
, range(1,5,2) [1,3].
, . .
, for ' - for i in range(1,5)
for i in [1, 2, 3, 4] ( )
i i.
, .
else . ,
for, break .
for..in .
range,
!
.
C/C++/Java/C#
Python, for for C/C++.
C# for Python foreach
C#. Java for (int i :
IntArray) Java 1.5 .
C/C++, .. for (int i = 0; i < 5; i++), Python
for i in range(0,5). , for ,
Python.
break
break , .
False ()
' .
for while ' ,
else .
:
#!/usr/bin/python
# Filename: break.py
while True:
s = (input('Enter something : '))
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
Python el: 35
$ 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 12
Enter something : quit
Done
:
'
(. ).
, 'quit'.
.
len .
break for.
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
continue
continue Python
.
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: continue.py
while True:
s = input(' : ')
if s == 'quit':
break
if len(s) < 3:
print(' ')
continue
Python el: 36
print(' ')
#
$ python test.py
: a
: 12
: abc
: quit
:
' , ,
3 . , len
3,
continue. ,
' .
continue for.
- if, while for
break continue.
Python ' ' .
.
Python el: 37
Python el:
.
,
. (calling) .
len range.
( ), '
.
def,
, (:).
.
:
:
#!/usr/bin/python
# Filename: function1.py
def sayHello():
print('Hello World!') #
#
sayHello() #
sayHello() #
$ python function1.py
Hello World!
Hello World!
:
O sayHello .
'
.
.
,
.
Python el: 38
, ,
. ,
.
. .
:
.
:
#!/usr/bin/python
# Filename: func_param.py
printMax(3, 4) # '
x = 5
y = 7
printMax(x, y) #
$ python func_param.py
4
7
:
printMax a b. B
if..else
.
printMax, , .
, . printMax(x, y)
x a y b. H
printMax .
Python el: 39
(Local variables)
,
,
. (scope)
. ,
.
:
#!/usr/bin/python
# Filename: func_local.py
x = 50
def func(x):
print(' x ', x)
x = 2
print(' x ', x)
func(x)
print(' x ', x)
$ python func_local.py
x 50
x 2
x 50
:
, x, Python
.
2 x. x .
x , x .
print, x
.
global
( ),
Python (global). global.
global.
( ). ,
. global
.
:
Python el: 40
#!/usr/bin/python
# Filename: func_global.py
x = 50
def func():
global x
print(' x ', x)
x = 2
print(' x ', x)
func()
print(' x ', x)
$ python func_global.py
x 50
x 2
x 2
:
global x , '
x ,
x .
global. global x, y, z.
nonlocal
.
(nonlocal scope)
.
.
Python , .
:
#!/usr/bin/python
# Filename: func_nonlocal.py
def func_outer():
x = 2
print(' x ', x)
def func_inner():
nonlocal x
x = 5
Python el: 41
func_inner()
print(' x ', x)
func_outer()
$ python func_nonlocal.py
x 2
x 5
:
func_inner, 'x' func_outer,
. x nonlocal x
.
nonlocal x global x,
, .
.
.
,
(=) .
.
-
. , .
:
#!/usr/bin/python
# Filename: func_default.py
say('Hello')
say('World', 5)
$ python func_default.py
Hello
WorldWorldWorldWorldWorld
:
say ,
. , .
1 times.
Python el: 42
say
. say 5
(say) 5 .
, ,
,
,
.
. def
func(a, b=5) def func(a=5, b) .
- (Keyword Arguments)
, , .
(keyword) ( )
.
,
. ,
, .
:
#!/usr/bin/python
# Filename: func_key.py
func(3, 7)
func(25, c=24)
func(c=50, a=100)
$ python func_key.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.
Python el: 43
func(c=50, a=100) ,
. c a
a c .
VarArgs
.
*.
:
#!/usr/bin/python
# Filename: total.py
$ python total.py
166
:
, *param,
, 'param'.
**param, ,
'param'.
.
-
-
,
.
:
#!/usr/bin/python
# Filename: keyword_only.py
print(total(10, 1, 2, 3, vegetables=50))
print(total(10, 1, 2, 3))
# Raises error because we have not supplied a default argument value
for 'vegetables'
$ python keyword_only.py
66
Traceback (most recent call last):
File "keyword_only.py", line 12, in <module>
total(10, 1, 2, 3)
TypeError: total() needs keyword-only argument vegetables
:
,
. ,
- , .
- ,
, def total(initial=5, *,
vegetables).
return
return ,
. , , .
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: func_return.py
print(maximum(2, 3))
:
Python el: 45
$ python func_return.py
3
:
maximum (maximum) ,
. if..else
' .
return return None. None
Python . ,
None.
K return None
. print(someFunction())
someFunction return:
def someFunction():
pass
pass Python .
max
, .
(DocStrings)
Python (documentation
strings) DocStrings.
.
, !
:
#!/usr/bin/python
# Filename: func_doc.py
O .'''
x = int(x) #
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')
printMax(3, 5)
print(printMax.__doc__)
Python el: 46
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
:
M
. (modules)
(classes), .
,
.
.
(non-trivial functions).
printMax
( ) __doc__ (
) . Python ,
.
.
help() Python,
. help() __doc__
. M
help(printMax) . q
help.
.
. pydoc Python help()
docstrings.
(Annotations)
,
. Python (
(third-party libraries),
), ' .
, Python Enhancement
Proposal No. 3107 [1].
Python el: 47
.
Python .
(modules)
Python.
References
[1] http:/ / www. python. org/ dev/ peps/ pep-3107/
Python el:
.
; .
,
.py .
o
Python. C
[1]
, Python
Python.
.
Python. A
.
:
#!/usr/bin/python
# Filename: using_sys.py
import sys
are
arguments
:
A sys import.
Python . sys
Python . system.
Python import sys, sys. ,
, Python .
. Python,
Python sys.path.
. .
argv sys . sys.argv.
sys.
argv
.
sys.argv (
. E sys.argv
(command line arguments) .
.
. import
os; print(os.getcwd()) .
yte .pyc
, Python
. byte (byte-compiled files)
.pyc Python
( Python).
.pyc .
.
byte-compiled (platform-independent).
.pyc .py.
Python , .pyc
.
(module's__name__)
.
. , ,
.
. __name__
.
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: using_name.py
if __name__ == '__main__':
print('A ')
else:
print(' ')
:
Python el: 50
$ python using_name.py
$ python
>>> import using_name
>>>
:
Python __name__, '__main__',
.
, ,
Python . .py.
.
:
#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print('Hi, this is mymodule speaking.')
__version__ = '0.1'
# End of mymodule.py
'.
Python. K
Python.
,
sys.path.
:
#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print ('Version', mymodule.__version__)
$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
Python el: 51
.
Python
Pyth , .
from..import:
#!/usr/bin/python
# Filename: mymodule_demo2.py
sayhi()
print('Version', __version__)
T mymodule_demo2.py mymodule_demo.py.
__version__
mymodule, .
. '
import .
:
sayhi __version__
.
Zen Python
Python
(Explicit is better than Implicit). import this
[2] Python.
dir
dir
. , ,
, .
dir,
. ,
.
:
$ python
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__',
'__package__', '__s
tderr__', '__stdin__', '__stdout__', '_clear_type_cache',
'_compact_freelists',
Python el: 52
>>> dir() #
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>> a = 5 # 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'sys']
>>> del a #
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>>
:
dir dir. M
.
dir . ,
.
.
dir, a ' ,
dir .
/ del
dir.
del: /
, del a, a
Python el: 53
.
dir() . ,
dir(print) print, dir(str)
str.
(Packages)
M ,
. .
.
; ' .
__init__.py Python
Python.
'world'
'asia', 'africa', ... 'india', 'madagascar',
...
:
T .
.
,
. .
Python .
.
.
Python el: 54
References
[1] http:/ / docs. python. org/ extending/
[2] http:/ / stackoverflow. com/ questions/ 228181/ zen-of-python
Python el:
,
.
.
Python, , ,
. .
,
(sequence) .
, ,
, Python
.
( [ ] ) Python
. ,
' .
, (mutable data type),
.
(objects) (classes)
,
.
.
. i
' , 5,
(. (instance)) i (. (type)) int.
help(int) .
M (methods),
.
. Python append
list, . ,
mylist.append('an item') mylist.
.
Python el: 55
(fields),
.
/ .
, , mylist.field.
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: using_list.py
#
shoplist = ['', '', '', '']
print(' ')
shoplist.sort()
print(' ', shoplist)
$ python using_list.py
' 4 .
:
' .
: ['', '', '',
'', '']
['', '', '',
'', '']
'
['', '', '', '']
:
Python el: 56
H shoplist . shoplist
,
.
for..in .
, .
.
- end print,
(end) (space) (line
break).
append ,
. , ,
, print .
, sort .
,
.
(mutable) (immutable).
, , .
del.
del .
del shoplist[0] ( Python
).
,
help(list) .
.
, .
,
.
,
.
, ,
, .
.
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: using_tuple.py
print(' ',
len(new_zoo))
print(' ', new_zoo)
print(' ',
new_zoo[2])
print(' ',
new_zoo[2][2])
print(' ',
len(new_zoo)-1+len(new_zoo[2]))
$ python using_tuple.py
3
3
('', '',
('', '', ''))
('',
'', '')
5
:
zoo . len
.
.
. , the
new_zoo ,
. ,
.
,
, .
(indexing operator). new_zoo new_zoo[2]
new_zoo
new_zoo[2][2]. A .
,
, . , print(1,2,3)
print( (1,2,3) ) - ,
( ).
0 1
myempty = (). ,
.
, Python
,
singleton = (2 , ), 2.
Python el: 58
Perl
.
Perl. , ,
, ... , Python,
, .
, /, ()
(). ,
.
( )
,
. .
d = {key1 :
value1, key2 : value2 }. -
.
- .
, .
/ dict.
:
#!/usr/bin/python
# Filename: using_dict.py
ab = { 'Swaroop' : 'swaroop@swaroopch.com',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
if 'Guido' in ab:
print("\nGuido's address is", ab['Guido'])
$ python using_dict.py
Swaroop's address is swaroop@swaroopch.com
:
ab .
- , (indexing operator)
. .
- , del. E
del. .
, - items ,
, -
. name
() address () , for..in
for.
-,
' , Guido
.
- , in,
has_key dict.
dict help(dict).
, ,
! , -
, (
).
Python el: 60
, ,
;
T (membership tests, . in
not in) (indexing operations). H
' .
, ,
(slicing operation), (slice)
.
:
#!/usr/bin/python
# Filename: 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[:])
# Slicing on a string
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[:])
$ python 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
Python el: 61
:
.
(subscription operation).
, , Python
. Python
. shoplist[0] shoplist[3]
shoplist.
, ,
. , shoplist[-1]
shoplist[-2] .
,
, .
, .
.
( )
(slice) ( ) .
, Python .
, Python .
,
.
shoplist[1:3] 1,
2, 3, , . ,
shoplist[:] .
.
. , shoplist[:-1]
, .
, (step)
( 1):
2, 0, 2, ...
3, 0, 3, ...
,
Python , . (prompt)
. ,
.
(Set)
.
.
, (membership), (subset)
, (intersection) .
:
To ,
.
(References)
,
' . H
, . (binding)
.
,
.
:
#!/usr/bin/python
# Filename: reference.py
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same
Python el: 63
object!
$ python 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']
:
.
, ,
( ),
. ,
,
.
Perl
.
.
Python el: 64
(strings) .
; ,
, !
str.
.
, help(str).
:
#!/usr/bin/python
# Filename: str_methods.py
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 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
:
E . startswith
. in
.
find
-1 (substring). str
join ,
(delimiter) ,
.
Python el: 65
Python .
.
Python,
Python.
Python el:
Python
.
Python.
"
".
, .
. ,
; ; ;
, .
. ,
. , ,
, , .
1. .
2. .
3. .
4. .
5. zip Linux/Unix.
Windows [1] [2]
C:\Program Files\GnuWin32\bin
, Python.
,
.
,
.
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
Python el: 66
# 1.
source = ['"C:\\My Documents"', 'C:\\Code']
#
# 2.
target_dir = 'E:\\Backup' #
# 3.
# 4.
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. zip
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
#
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
$ python backup_ver1.py
Successful backup to E:\Backup\20080702185040.zip
.
, (debug) ,
(bugs) .
, print(zip_command)
os.system . , zip_command
. ,
zip . ,
.
:
.
os time . ,
source. ,
, target_dir.
time.strftime(). .zip
target_dir.
Python el: 67
os.sep - '/'
Linux Unix, '\\' Windows ':' Mac OS. os.sep
.
time.strftime()
. %Y .
%m 01 12 ' .
Python [3].
(+),
, .
, zip_command
. ( Linux
DOS).
zip . -q
(quietly). -r
(recursively) , .
-qr.
. source join
. .
, os.system
, 0 ,
.
,
.
,
!
Windows
,
. ,
'C:\\Documents' r'C:\Documents'. ,
'C:\Documents', \D.
,
. Linux/Unix ,
, ,
. .
, ()
. ,
.
.
Python el: 68
. , ,
. .
-
.
.
.
,
.
#!/usr/bin/python
# Filename: backup_ver2.py
import os
import time
# 1.
source = ['"C:\\My Documents"', 'C:\\Code']
#
# 2.
target_dir = 'E:\\Backup' #
# 3.
# 4.
today = target_dir + os.sep + time.strftime('%Y%m%d')
#
now = time.strftime('%H%M%S')
#
if not os.path.exists(today):
os.mkdir(today) # make directory
print('Successfully created directory', today)
#
target = today + os.sep + now + '.zip'
# 5. zip
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
Python el: 69
#
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
$ python backup_ver2.py
Successfully created directory E:\Backup\20080702
Successful backup to E:\Backup\20080702\202311.zip
$ python backup_ver2.py
Successful backup to E:\Backup\20080702\202325.zip
:
.
os.path.exists. , os.mkdir.
,
, . ,
.
.
, ,
.
#!/usr/bin/python
# Filename: backup_ver3.py
import os
import time
# 1.
source = ['"C:\\My Documents"', 'C:\\Code']
#
# 2.
target_dir = 'E:\\Backup' #
Python el: 70
# 3.
# 4.
today = target_dir + os.sep + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
#
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) # make directory
print('Successfully created directory', today)
# 5. zip
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
#
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
$ python backup_ver3.py
File "backup_ver3.py", line 25
target = today + os.sep + now + '_' +
^
SyntaxError: invalid syntax
() :
! Python ,
Python. ,
. .
,
. , Python (+)
' .
. . ,
Python el: 71
, .
#!/usr/bin/python
# Filename: backup_ver4.py
import os
import time
# 1.
source = ['"C:\\My Documents"', 'C:\\Code']
#
# 2.
target_dir = 'E:\\Backup' #
# 3.
# 4.
today = target_dir + os.sep + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
#
comment = input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'
#
if not os.path.exists(today):
os.mkdir(today) # make directory
print('Successfully created directory', today)
# 5. zip
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
#
if os.system(zip_command) == 0:
Python el: 72
$ python backup_ver4.py
Enter a comment --> added new examples
Successful backup to E:\Backup\20080702\202836_added_new_examples.zip
$ python backup_ver4.py
Enter a comment -->
Successful backup to E:\Backup\20080702\202839.zip
:
! .
input
len .
enter (
), .
, ,
.zip. (underscores),
.
,
. ,
, -v .
. sys.argv
source extend list.
os.system
, ' zipfile tarfile.
, ,
.
, os.system
,
.
zipfile [4]
os.system;
Python el: 73
.
:
1. ()
2. ()
3. ()
4. ( )
5. ( )
6. ()
: .
. .
.
-- . ,
.
/ Python
.
, Python
.
.
References
[1] http:/ / gnuwin32. sourceforge. net/ downlinks/ zip. php
[2] http:/ / gnuwin32. sourceforge. net/ packages/ zip. htm
[3] http:/ / docs. python. org/ 3. 0/ library/ time. html#time. strftime
[4] http:/ / docs. python. org/ 3. 0/ library/ zipfile. html
Python el: 74
Python el:
, ,
. .
,
. .
,
,
.
.
, (instances) .
int
() int.
( int).
C++ Java ( 1.5),
(primitive native types). help(int)
.
C# Java 1.5 boxing and unboxing .
.
(fields).
.
.
. ,
(attributes) .
- / .
(instance variables) .
- class.
.
self
-
,
, Python.
, self.
,
self - .
-
. (Integrated Development Environments)
, self.
C++/Java/C#
Python el: 75
#!/usr/bin/python
# Filename: simplestclass.py
class Person:
pass #
p = Person()
print(p)
$ python simplestclass.py
<__main__.Person object at 0x019F85F0>
:
class .
.
pass.
, /
. (
). , .
Person __main__.
.
Python
.
/ ,
self. .
#!/usr/bin/python
# Filename: method.py
class Person:
def sayHi(self):
Python el: 76
p = Person()
p.sayHi()
#
Person().sayHi()
$ python method.py
Hello, how are you?
:
self . sayHi ,
self .
__init__
Python.
__init__.
__init__ .
.
.
:
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print('Hello, my name is', self.name)
p = Person('Swaroop')
p.sayHi()
#
Person('Swaroop').sayHi()
$ python class_init.py
Hello, my name is Swaroop
:
__init__ name ( self). ,
name.
'name'.
Python el: 77
( ),
. , ,
(namespaces) .
. '
name spaces.
(fields) -
.
-
.
, .
/ .
, ,
.
:
#!/usr/bin/python
# Filename: objvar.py
class Robot:
'''Represents a robot, with a name.'''
# ,
population = 0
# ,
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Python el: 78
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots
working.'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot.
def howMany():
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()
Robot.howMany()
(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)
.
, population Robot.population
self.population. name self.name
.
.
!
howMany .
classmethod staticmethod,
. ,
staticmethod.
(decorators) [1]:
@staticmethod
def howMany():
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))
(explicit
statement), .
__init__ Robot
. , population 1,
. self.name ,
.
self . (attribute reference).
, docstrings .
docstring
Robot.__doc__ docstring Robot.sayHi.__doc__
__init__, __del__
,
. , Robot.population 1.
__del__
. , del
.
C++/Java/C#
Python el: 80
(Inheritance)
(reuse)
.
(type and subtype) .
.
- , . , -
, , .
,
. .
SchoolMember
,
() .
. /
SchoolMember, . ,
SchoolMember. , .
SchoolMember,
. (polymorphism)
,
.
, .
SchoolMember (base class)
(superclass). Teacher Student (derived classes)
(subclasses).
.
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
Python el: 81
self.name = name
self.age = age
print('(Initialized SchoolMember: {0})'.format(self.name))
def tell(self):
'''Tell my details.'''
print('Name:"{0}" Age:"{1}"'.format(self.name, self.age), end="
")
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {0})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary: "{0:d}"'.format(self.salary))
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('(Initialized Student: {0})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Marks: "{0:d}"'.format(self.marks))
print() #
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
$ python inherit.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Python el: 82
:
, ,
. , __init__
self
. Python
, .
, self .
Teacher Student
SchoolMember, tell SchoolMember.
, tell tell
SchoolMember. Python
, . ,
.
-
, .
,
.
. Python
.
/ Python.
References
[1] http:/ / www. ibm. com/ developerworks/ linux/ library/ l-cpdecor. html
Python el: 83
Python el:
. ,
.
input() print().
str (string). ,
rjust ,
(right justified) . help(str)
.
/ (files).
,
.
#!/usr/bin/python
# user_input.py
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
$ python user_input.py
Enter text: sir
No, it is not a palindrome
$ python user_input.py
Enter text: madam
Yes, it is a palindrome
$ python user_input.py
Enter text: racecar
Yes, it is a palindrome
:
Python el: 84
() .
, seq[a:b],
a b.
. 1
. . -1, .
input() .
return. ,
input() .
. ,
[1].
:
,
. , "Rise to vote, sir" ,
. ;
,
file , read, readline write
.
(mode) . ,
, close, Python
.
:
#!/usr/bin/python
# Filename: using_file.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
:
open
.
('r', read mode), ('w', write mode) ('a', append mode).
('t', text file) ('b', binary file).
help(open)
. open() ('t'ext file)
'r'ead.
, write
, (close) .
. ,
'' .
readline .
(newline character) .
, '' (break) .
print() (newline)
. end='',
. , (close) .
, poem.txt,
.
Pickle
Python pickle
Python .
(persistently).
:
#!/usr/bin/python
# Filename: pickling.py
import pickle
$ python pickling.py
['apple', 'mango', 'carrot']
:
, (open)
'w'rite 'b'inary dump pickle.
pickling.
, load pickle,
. unpickling.
/,
pickle.
(exceptions).
References
[1] http:/ / en. wiktionary. org/ wiki/ palindrome
Python el: 87
Python el:
.
, ;
;
.
, ; Python
.
print. Print
print; P p. Python (raises)
(syntax error).
NameError
. (error handler) .
(try) . ctrl-d .
Python , EOFError,
end of file ( ctrl-d), .
Python el: 88
try..except. ,
try except.
#!/usr/bin/python
# Filename: try_except.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 {0}'.format(text))
$ python try_except.py
Enter something --> # Press ctrl-d
Why did you do an EOF on me?
$ python try_except.py
Enter something --> # Press ctrl-c
You cancelled the operation.
$ python try_except.py
Enter something --> no exceptions
You entered no exceptions
:
, / try
/ / except.
except ,
/ .
, except .
except try.
try;
, Python,
.
.
else try..except. H
else .
, ,
.
Python el: 89
(Raising Exceptions)
raise,
/ .
, ,
Exception.
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
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)
# Other work can continue as usual here
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 raising.py
Enter something --> a
ShortInputException: The input was 1 long, expected at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
:
.
ShortInputException. , length,
atleast .
except, (as)
/.
. except,
length atleast ,
Python el: 90
Try .. Finally
.
, ;
finally. except
finally try. ,
.
#!/usr/bin/python
# Filename: finally.py
import time
try:
f = open('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
print(line, end='')
time.sleep(2) # To make sure it runs for a while
except KeyboardInterrupt:
print('!! You cancelled the reading from the file.')
finally:
f.close()
print('(Cleaning up: Closed the file)')
$ python finally.py
Programming is fun
When the work is done
if you wanna make your work also fun:
!! You cancelled the reading from the file.
(Cleaning up: Closed the file)
:
, 2
, time.sleep
( Python ). , ctrl-c
/ .
KeyboardInterrupt . ,
, finally
.
Python el: 91
with
try
finally . ' with,
:
#!/usr/bin/python
# Filename: using_with.py
with open("poem.txt") as f:
for line in f:
print(line, end='')
:
.
open with. A with
open.
with. open. thefile
.
thefile.__enter__ ,
thefile.__exit__, .
finally
__exit__.
try..finally .
,
PEP343 [1] .
try..except try..finally.
, , .
Python (Python Standard Library).
References
[1] http:/ / www. python. org/ dev/ peps/ pep-0343/
Python el: 92
Python el:
Python --~~~~Insert
non-formatted text here--~~~~--~~~~--~~~~--~~~~ ---- ---- ---- ---- [[[http://www.example.com link title]]]
Python. ,
.
.
, 'Library Reference' section
[1]
Python.
A .
(advanced)
. , ,
Python.
sys
sys . sys.argv
.
Python ,
3. sys
.
:
T sys version_info .
. , ,
Python 3.0:
#!/usr/bin/python
# Filename: versioncheck.py
import sys, warnings
if sys.version_info[0] < 3:
warnings.warn("Need Python 3.0 for this program to run",
RuntimeWarning)
else:
print('Proceed as normal')
:
Python el: 93
$ python2.5 versioncheck.py
versioncheck.py:6: RuntimeWarning: Need Python 3.0 for this program
to run
RuntimeWarning)
$ python3 versioncheck.py
Proceed as normal
:
warnings,
. Python
3, .
logging
T
, ;
; logging:
#!/usr/bin/python
# Filename: use_logging.py
import os, platform, 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 use_logging.py
Logging to C:\Users\swaroop\test.log
test.log, :
:
- os
, platform ,
, logging (log).
, ,
platform.platform() ( , import platform;
help(platform)). Windows home drive, home
(filename) . ,
. ,
home .
os.path.join()
. ,
,
(format) .
logging
.
, , ,
, . ,
,
.
urllib json
; .
. urllib,
.
Yaho! Search
JSON,
, json .
TODO
(bug) Python 3.0 beta 2 [2].
#!/usr/bin/python
# Filename: yahoo_search.py
import sys
if sys.version_info[0] != 3:
sys.exit('This program needs Python 3.0')
import json
import urllib, urllib.parse, urllib.request, urllib.response
'jl22psvV34HELWhdfUJbfDQzlJ2B57KFS_qs4I8D0Wz5U5_yCI1Awv8.lBSfPhwr'
SEARCH_BASE =
'http://search.yahooapis.com/WebSearchService/V1/webSearch'
class YahooSearchError(Exception):
pass
:
TODO
:
,
. ,
key1=value1&key2=value2,
urllib.parse.urlencode().
, [3] 20 ,
, byte of python,
JSON.
K (URL)
urllib.request.urlopen() json.load(),
Python.
.
Python el: 96
[4]
,
[5], [6] ...
,
Doug Hellmann's, Python Module of the Week [7].
Python.
Python Standard Library [1],
.
Python, Python
.
References
[1] http:/ / docs. python. org/ 3. 0/ library/
[2] http:/ / bugs. python. org/ issue3763
[3] http:/ / search. yahooapis. com/ WebSearchService/ V1/ webSearch?query=byte+ of+ python&
appid=jl22psvV34HELWhdfUJbfDQzlJ2B57KFS_qs4I8D0Wz5U5_yCI1Awv8. lBSfPhwr& results=20& start=1& output=json
[4] http:/ / docs. python. org/ dev/ library/ pdb. html
[5] http:/ / docs. python. org/ 3. 0/ library/ getopt. html
[6] http:/ / www. diveintopython. org/ regular_expressions/ index. html
[7] http:/ / www. doughellmann. com/ projects/ PyMOTW/
Python el: 97
Python el:
Python .
, Python .
; .
.
a, b = < >
.
(a, < >),
, :
>>> a, *b = [1, 2, 3, 4]
>>> a
1
>>> b
[2, 3, 4]
Python
:
>>> a = 5; b = 8
>>> a, b = b, a
>>> a, b
(8, 5)
__init__ __del__ .
. ,
x[key] (
),
__getitem__() . , Python
list!
.
[1].
Python el: 98
__init__(self, ...) .
__del__(self)
__getitem__(self, x[key].
key)
__len__(self) len() .
.
, . ,
, .
:
.
"",
, ,
.
Lambda Forms
lambda
.
#!/usr/bin/python
# Filename: lambda.py
def make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)
print(twice('word'))
print(twice(5))
$ python lambda.py
wordword
10
Python el: 99
:
make_repeater
. lambda
. lambda
. print
lambda, .
TODO
list.sort()
lambda;
(List comprehension) .
2 2.
.
#!/usr/bin/python
# Filename: list_comprehension.py
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)
$ python list_comprehension.py
[6, 8]
:
, (2*i) (if i > 2).
.
.
* ** .
.
* args,
args . **,
- .
exec eval
exec Python
, . ,
Python ,
exec:
, eval Python
. .
>>> eval('2*3')
6
assert
assert . ,
, , assert '
. assert , AssertionError.
assert .
,
' .
Python el: 101
repr
repr
. eval(repr(object)) == object
.
>>> i = []
>>> i.append('item')
>>> repr(i)
"['item']"
>>> eval(repr(i))
['item']
>>> eval(repr(i)) == i
True
, repr
.
repr __repr__ .
Python ' ,
. , '
. .
, Python .
References
[1] http:/ / docs. python. org/ 3. 0/ reference/ datamodel. html#special-method-names
Python el: 102
Python el:
,
, Python.
Python .
, . ; !
:
,
, , ,
, , ,
/ .
.
.
, :
( )
.
.
pickle .
, .
, Python.
email [2] ;-) .
. , ,
.
, :
replace [1].
.
,
( ).
' , Python:
:
PLEAC [2]
Rosetta [3]
Python java2s [4]
Python Cookbook [5]
Python. Python .
Python el: 103
Python [6]
Python [7]
Norvig [8]
Python [9]
Python StackOverflow [10]
Python [11]
Python [12]
Charming Python [13] Python David Mertz.
, ,
Dive Into Python
[14]
Mark Pilgrim . Dive Into Python
, XML, , unit testing,
.. .
:
ShowMeDo Python [15]
GoogleTechTalks Python [16]
Python Awaretek [17]
Effbot's Python Zone [18]
Python-URL! [19]
Python Papers [20]
' Python, ,
comp.lang.python [21] .
.
Python,
Python [22] / [http://www.planetpython.org Python.
Python el: 104
[5]
Python
.
EasyInstall [23] Philip J. Eby.
Python.
GUI (Graphical User Interface, )
Python. (bindings)
Python C C++ .
GUI Python:
PyQt
Python Qt
KDE. Qt Qt Designer
. PyQt
( GPL)
. Qt 4.5 ,
GPL. , PyQt [24]
PyQt. PyGTK Python GTK+
GNOME. GTK+ ,
GUI . Glade
. . GTK+ Linux
Windows .
GTK+. [http://www.pygtk.org/tutorial.html
PyGTK [25].
wxPython
Python wxWidgets. wxPython .
, , Linux, Windows, Mac
. IDE wxPython GUI
SPE (Stani's Python Editor) [26] GUI wxGlade [27].
wxPython.
, wxPython [28].
TkInter
GUI .
IDLE, TkInter .
. TkInter both
Linux/Unix Windows, TkInter Python.
, Tkinter [29].
, GuiProgramming wiki
Python [30].
Python el: 105
GUI
GUI Python.
, .
GUI.
Windows, Mac, Linux, . ,
Linux, KDE GNOME.
, 26 The Python Papers, 3, 1 [31].
: .
. .
CPython . '
CPython C Python.
:
Jython [32]
Python Java.
Java Python .
IronPython [33]
Python .NET.
.NET Python .
PyPy [34]
Python Python!
( C, Java C#
).
Stackless Python [35]
Python .
, CLPython [36] - Python Common Lisp-
IronMonkey [37] IronPython
JavaScript Python ( JavaScript)
("Ajax").
.
, Python.
Python
Python.
, , !
, ;
Python el: 106
References
[1] http:/ / unixhelp. ed. ac. uk/ CGI/ man-cgi?replace
[2] http:/ / pleac. sourceforge. net/ pleac_python/ index. html
[3] http:/ / www. rosettacode. org/ wiki/ Category:Python
[4] http:/ / www. java2s. com/ Code/ Python/ CatalogPython. htm
[5] http:/ / code. activestate. com/ recipes/ langs/ python/
[6] http:/ / docs. python. org/ dev/ howto/ doanddont. html
[7] http:/ / www. python. org/ doc/ faq/ general/
[8] http:/ / norvig. com/ python-iaq. html
[9] http:/ / dev. fyicenter. com/ Interview-Questions/ Python/ index. html
[10] http:/ / beta. stackoverflow. com/ questions/ tagged/ python
[11] http:/ / www. siafoo. net/ article/ 52
[12] http:/ / ivory. idyll. org/ articles/ advanced-swc/
[13] http:/ / gnosis. cx/ publish/ tech_index_cp. html
[14] http:/ / www. diveintopython. org
[15] http:/ / showmedo. com/ videos/ python
[16] http:/ / youtube. com/ results?search_query=googletechtalks+ python
[17] http:/ / www. awaretek. com/ tutorials. html
[18] http:/ / effbot. org/ zone/
[19] http:/ / groups. google. com/ group/ comp. lang. python. announce/ t/ 37de95ef0326293d
[20] http:/ / pythonpapers. org
[21] http:/ / groups. google. com/ group/ comp. lang. python/ topics
[22] http:/ / planet. python. org
[23] http:/ / peak. telecommunity. com/ DevCenter/ EasyInstall#using-easy-install
[24] http:/ / zetcode. com/ tutorials/ pyqt4/
[25] http:/ / www. qtrac. eu/ pyqtbook. html
[26] http:/ / spe. pycs. net/
[27] http:/ / wxglade. sourceforge. net/
[28] http:/ / zetcode. com/ wxpython/
[29] http:/ / www. pythonware. com/ library/ tkinter/ introduction/
[30] http:/ / www. python. org/ cgi-bin/ moinmoin/ GuiProgramming
[31] http:/ / archive. pythonpapers. org/ ThePythonPapersVolume1Issue1. pdf
[32] http:/ / www. jython. org
[33] http:/ / www. codeplex. com/ Wiki/ View. aspx?ProjectName=IronPython
[34] http:/ / codespeak. net/ pypy/ dist/ pypy/ doc/ home. html
[35] http:/ / www. stackless. com
[36] http:/ / common-lisp. net/ project/ clpython/
[37] http:/ / wiki. mozilla. org/ Tamarin:IronMonkey
Python el: 107
Python el:
, .
, ,
.
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z
A
and
: and False False,
.
arguments
assignment
: . x = 2
x.
associativity
: . Python,
,
B
block
bug
C
class
complex number
concatenation
constant
Python el: 108
D
data type
debug
declaration
definition
dictionary
E
escape sequence
exponentiation
: **
. 2 ** 3
" " 8.
expression
F
floating point
floor division
: //
( ) .
function
identifier
immutable
integer
Python el: 109
L
lambda
list
literal constant
loop
M
method
module
O
object
operand
:
(..). 2 + 3 2 3 .
.
operator
: .
+ , .
or
: or True True,
.
.
output
Python el: 110
Q
quotes
R
raw string
regular expression
S
scope
slicing
: (, , )
.
statement
string
T
tab
: o /t
tuple
V
variable
Python el: 111
Python el:
/ ()
To [1] , .
, .
, Python,
Python !
:
Linux. !
Linus Torvalds . Microsoft
Windows. [Linux Kernel [2]]
Ubuntu. Linux , Canonical
.
.
Live-CD!
. [Ubuntu Linux [3]]
OpenOffice.org. , ,
, . MS
Word MS PowerPoint. . [OpenOffice [4]]
Mozilla Firefox. Internet Explorer.
.
.
Thunderbird .
[Mozilla Firefox [5], Mozilla Thunderbird [6]]
Mono. .NET.
.NET Linux, Windows, FreeBSD, Mac OS . [Mono [7], ECMA [8],
Microsoft .NET [9]]
Apache web server. . ,
!
. , - Apache '
( Microsoft IIS). [Apache [10]]
MySQL. . .
M LAMP (Linux-Apache-MySql-PHP)
. [MySQL [11]]
VLC Player. . : DivX, MP3, Ogg,
VCDs, DVDs... ; ;-) [VLC media
player [12]]
GeexBox Linux CD!
[GeexBox [13]]
- ,
Perl PHP, Drupal,
PostgreSQL, TORCS,
KDevelop, Xine, VIM Quanta+,
Python el: 112
References
[1] http:/ / en. wikipedia. org/ wiki/ FLOSS
[2] http:/ / www. kernel. org
[3] http:/ / www. ubuntu. com
[4] http:/ / www. openoffice. org
[5] http:/ / www. mozilla. org/ products/ firefox
[6] http:/ / www. mozilla. org/ products/ thunderbird
[7] http:/ / www. mono-project. com
[8] http:/ / www. ecma-international. org
[9] http:/ / www. microsoft. com/ net
[10] http:/ / httpd. apache. org
[11] http:/ / www. mysql. com
[12] http:/ / www. videolan. org/ vlc/
[13] http:/ / geexbox. org/ en/ start. html
[14] http:/ / www. linux. com
[15] http:/ / www. linuxtoday. com
[16] http:/ / www. newsforge. com
[17] http:/ / www. distrowatch. com
[18] http:/ / www. ellak. gr
[19] http:/ / www. sourceforge. net
[20] http:/ / www. freshmeat. net
Python el: 113
Python el:
.
, Red Hat 9.0 Linux
, Fedora Core 3 Linux .
, KWord (
).
, DocBook XML Kate . ,
OpenOffice ,
PDF, HTML .
, XEmacs , DocBook XML ()
.
, Quanta+ .
XSL stylesheets Fedora Core 3 Linux. ,
CSS HTML.
, Python,
.
, MediaWiki [1] [2].
'
// wiki.
[3]
Vim , ViewSourceWith Firefox
Vim.
http://www.swaroopch.com/about/
References
[1] http:/ / www. mediawiki. org
[2] http:/ / www. swaroopch. com/ notes/
[3] https:/ / addons. mozilla. org/ en-US/ firefox/ addon/ 394
Python el: 114
Python el:
1.90
04/09/2008
3.5 !
Python 3.0
MediaWiki ()
1.20
13/01/2005
Quanta+ FC3 .
. DocBook .
1.15
28/03/2004
.
1.12
16/03/2004
.
1.10
09/03/2004
, .
1.00
08/03/2004
,
, .
0.99
22/02/2004
.
.
0.98
16/02/2004
Python CSS stylesheet XHTML,
VIM .
0.97
13/02/2004
, DocBook XML ().
- .
0.93
25/01/2004
IDLE Windows.
0.92
05/01/2004
.
0.91
Python el: 115
30/12/2003
. .
0.90
18/12/2003
2 . OpenOffice .
0.60
21/11/2003
.
0.20
20/11/2003
.
0.15
20/11/2003
DocBook XML.
0.10
14/11/2003
KWord.
Article Sources and Contributors 116
Python el: Source: http://www.swaroopch.com/mediawiki/index.php?oldid=4246 Contributors: Fstefanidis, Midkin, Ubuntu-gr.org, 13 anonymous edits
Python el: Source: http://www.swaroopch.com/mediawiki/index.php?oldid=4292 Contributors: Konsnos, Midkin, Ubuntu-gr.org, 1 anonymous edits
License
Creative Commons Attribution-Share Alike 3.0 Unported
http:/ / creativecommons. org/ licenses/ by-sa/ 3. 0/