Python 2.6 Quick Reference (Letter) (2009).pdf
(
893 KB
)
Pobierz
Python 2.6 Quick Reference
Python 2.6 Quick Reference
Python 2.6 Quick Reference
Contents
Front matter
Invocation Options
Environment variables
Lexical entities
:
keywords
,
identifiers
,
string literals
,
boolean constants
,
numbers
,
sequences
,
dictionaries
,
operators
Basic types
and their operations:
None
,
bool
,
Numeric types
,
sequence types
,
list
,
dictionary
,
string
,
file
,
set
,
named tuples
,
date/time
Advanced types
Statements
: assignment
,
conditional expressions
,
control flow
,
exceptions
,
name space
,
function def
,
class def
Iterators
;
Generators
;
Descriptors
;
Decorators
Built-in Functions
Built-in Exceptions
Standard
methods & operators redefinition
in usercreated Classes
Special
informative state attributes
for some types
Important
modules
:
sys
,
os
,
posix
,
posixpath
,
shutil
,
time
,
string
,
re
,
math
,
getopt
List of modules
in the base distribution
Workspace exploration and idiom hints
Python mode for Emacs
Front matter
Version 2.6 (
What's new?
)
Check updates at
http://rgruet.free.fr/#QuickRef
.
Please
report
errors, inaccuracies and suggestions to
Richard Gruet
(pqr at rgruet.net).
Creative Commons License.
Last updated on February 10, 2009.
Feb 10, 2008
upgraded by Richard Gruet and
Josh Stone
for Python 2.6
Dec 14, 2006
upgraded by Richard Gruet for Python 2.5
Feb 17, 2005,
upgraded by Richard Gruet for Python 2.4
Oct 3, 2003
upgraded by Richard Gruet for Python 2.3
May 11, 2003, rev 4
upgraded by Richard Gruet for Python 2.2 (restyled by
Andrei
)
Aug 7, 2001
upgraded by Simon Brunning for Python 2.1
May 16, 2001
upgraded by Richard Gruet and
Simon Brunning
for Python 2.0
Jun 18, 2000
upgraded by
Richard Gruet
for Python 1.5.2
Oct 20, 1995
created by
Chris Hoffmann
for Python 1.3
Color coding:
Features added in 2.6 since 2.5
Features added in 2.5 since 2.4
Features added in 2.4 since 2.3
Originally based on:
Python Bestiary, author:
Ken Manheimer
Page 1 of 50
Python 2.6 Quick Reference
Python manuals
, authors:
Guido van Rossum
and Fred Drake
pythonmode.el, author:
Tim Peters
and the readers of
comp.lang.python
Useful links :
Python's nest
:
http://www.python.org
Official documentation
:
http://docs.python.org/2.6/
Other doc & free books
:
FAQs
,
Faqts
,
Dive into Python
,
Python Cookbook
,
Thinking in Python
,
Text processing in
Python
Getting started
:
Python Tutorial
,
7mn to Hello World (windows)
Topics
:
HOWTOs
,
Databases
,
Web programming
,
XML
,
Web Services
,
Parsers
,
Numeric & Scientific Computing
,
GUI
programming
,
Distributing
Where to find packages
:
Python Package Index (PyPI)
,
Python Eggs
,
SourceForge (search "python")
,
Easy Install
,
O'Reilly Python DevCenter
Wiki
:
moinmoin
Newsgroups
:
comp.lang.python
and
comp.lang.python.announce
Misc pages
:
Daily Python URL
Python Development
:
http://www.python.org/dev/
Jython
Java implementation of Python:
http://www.jython.org/
IronPython
Python on .Net:
http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython
ActivePython
:
http://www.ActiveState.com/ASPN/Python/
Help desk
:
help@python.org
2 excellent (but somehow outdated)
Python reference books
:
Python Essential Reference
(Python 2.1) by David
Beazley & Guido Van Rossum (Other New Riders) and
Python in a nutshell
by Alex martelli (O'Reilly).
Python 2.4 Reference Card (cheatsheet)
by Laurent Pointal, designed for printing (15 pages).
Online Python 2.2 Quick Reference
by the New Mexico Tech Computer Center.
Tip
: From within the Python interpreter, type
help
,
help(
object
)
or
help("
name
")
to get help.
Invocation Options
python
[
w
] [BdEhimOQsStuUvVWxX3?] [c
command
|
scriptFile
| ] [
args
]
(python
w
does not open a terminal/console; python does)
Invocation Options
Option Effect
B Prevents module imports from creating
.pyc
or
.pyo
files (see also envt variable
PYTHONDONTWRITEBYTECODE=x
and attribute
sys.dont_write_bytecode
).
d Output parser debugging information (also PYTHONDEBUG=x)
E Ignore environment variables (such as PYTHONPATH)
h Print a help message and exit (formerly ?)
i Inspect interactively after running script (also PYTHONINSPECT=x) and force prompts, even if stdin
appears not to be a terminal.
m
module
Search for
module
on
sys.path
and runs the module as a script. (Implementation improved in 2.5:
module
runpy
)
O Optimize generated bytecode (also PYTHONOPTIMIZE=x). Asserts are suppressed.
OO Remove docstrings in addition to the O optimizations.
Q
arg
Division options: Qold (default), Qwarn, Qwarnall, Qnew
s Disables the userspecific module path (also PYTHONNOUSERSITE=x)
S Don't perform
import site
on initialization.
t Issue warnings about inconsistent tab usage (tt: issue errors).
u Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x).
U Force Python to interpret all string literals as Unicode literals.
v Verbose (trace import statements) (also PYTHONVERBOSE=x).
V Print the Python version number and exit.
W
arg
Warning control (arg is action:message:category:module:lineno)
x
Skip first line of source, allowing use of nonunix Forms of
#!cmd
X
Disable class based builtin exceptions (for backward compatibility management of exceptions)
3
Emit a
DeprecationWarning
for Python 3.x incompatibilities
c
Specify the command to execute (see next section). This terminates the option list (following
Page 2 of 50
Python 2.6 Quick Reference
command
options are passed as arguments to the command).
scriptFile
The name of a python file (.py) to execute. Read from stdin.
-
Program read from stdin (default; interactive mode if a tty).
args
Passed to script or command (in
sys.argv[1:]
)
If no scriptFile or command, Python enters interactive mode.
Available
IDEs
in std distrib:
IDLE
(tkinter based, portable),
Pythonwin
(on Windows). Other free IDEs:
IPython
(enhanced interactive Python shell),
Eric
,
SPE
,
BOA constructor
,
PyDev
(Eclipse plugin).
Typical python
module header
:
#!/usr/bin/env python
# -*- coding: latin1 -*-
Since 2.3 the
encoding
of a Python source file must be declared as one of the two first lines (or defaults to
7
bits Ascii
) [
PEP0263
], with the format:
# -*- coding:
encoding
-*-
Std
encodings
are defined
here
, e.g. ISO88591 (aka latin1), iso885915 (latin9), UTF8... Not all encodings
supported, in particular UTF16 is not supported.
It's now a
syntax error
if a module contains string literals with 8bit characters but doesn't have an encoding
declaration (was a warning before).
Since 2.5,
from __future__ import
feature
statements must be declared at
beginning
of source file.
Site customization
: File
sitecustomize.py
is automatically loaded by Python if it exists in the Python path
(ideally located in
${PYTHONHOME}/lib/site-packages/
).
Tip:
when launching a Python script on Windows,
<pythonHome>\python myScript.py args ...
can be reduced to :
myScript.py args ...
if <pythonHome> is in the PATH envt variable, and further reduced to :
myScript args ...
provided that
.py;.pyw;.pyc;.pyo
is added to the
PATHEXT
envt variable.
Environment variables
Environment variables
Variable
Effect
PYTHONHOME
Alternate
prefix
directory (or
prefix
:
exec_prefix
). The default module search
path uses
prefix
/lib
PYTHONPATH
Augments the default search path for module files. The format is the same as
the shell's
$PATH
: one or more directory pathnames separated by ':' or ';'
without spaces around (semi) colons !
On Windows Python first searches for Registry key
HKEY_LOCAL_MACHINE\Software\Python\PythonCore\
x.y
\PythonPath
(default
value). You can create a key named after your application with a default string
value giving the root directory path of your appl.
Alternatively, you can create a text file with a
.pth
extension, containing the
path(s), one per line, and put the file somewhere in the Python search path
(ideally in the
site-packages/
directory). It's better to create a .pth for each
application, to make easy to uninstall them.
PYTHONSTARTUP If this is the name of a readable file, the Python commands in that file are
executed before the first prompt is displayed in interactive mode (no default).
PYTHONDEBUG If nonempty, same as d option
PYTHONINSPECT If nonempty, same as i option
PYTHONOPTIMIZE If nonempty, same as O option
PYTHONUNBUFFERED If nonempty, same as u option
PYTHONVERBOSE If nonempty, same as v option
PYTHONCASEOK If nonempty, ignore case in file/module names (imports)
PYTHONDONTWRITEBYTECODE If nonempty, same as B option
PYTHONIOENCODING
Alternate
encodingname
or
encodingname:errorhandler
for stdin, stdout, and
stderr, with the same choices accepted by
str.encode()
.
PYTHONUSERBASE
Provides a private
site-packages
directory for
user-specific
modules. [PEP
0370]
On Unix and Mac OS X, defaults to
~/.local/
, and modules are found in a
Page 3 of 50
Python 2.6 Quick Reference
versionspecific subdirectory like
lib/python2.6/site-packages
.
On Windows, defaults to
%APPDATA%/Python
and
Python26/site-packages
.
PYTHONNOUSERSITE
If nonempty, same as s option
Notable lexical entities
Keywords
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass with
def finally in print yield
(List of keywords available in std module:
keyword
)
Illegitimate Tokens (only valid in strings):
$ ?
(plus
@
before 2.4)
A statement must all be on a single line. To break a statement over multiple lines, use "
\
", as with the C
preprocessor.
Exception
: can always break when inside any (), [], or {} pair, or in triplequoted strings.
More than one statement can appear on a line if they are separated with semicolons ("
;
").
Comments start with "
#
" and continue to end of line.
Identifiers
(
letter
| "_") (
letter
|
digit
| "_")*
Python identifiers keywords, attributes, etc. are
case-sensitive
.
Special forms:
_
ident
(not imported by 'from module import *');
__
ident
__
(system defined name); __
ident
(classprivate name mangling).
String literals
Two flavors:
str
(standard 8 bits localedependent strings, like ascii, iso 88591, utf8, ...) and
unicode
(16 or 32
bits/char in utf16 mode or 32 bits/char in utf32 mode); one common ancestor
basestring
.
Literal
"
a string enclosed by double quotes
"
'
another string delimited by single quotes and with a " inside
'
'''
a string containing embedded newlines and quote (') marks, can be delimited with triple quotes.
'''
"""
may also use 3 double quotes as delimiters
"""
b"
An 8bit string
"
A
bytes
instance, a forwardcompatible form for an 8bit string
'
B"
Another 8bit string
"
u'
a
unicode
string
'
U"
Another
unicode
string
"
r'
a
raw
string where \ are kept (literalized): handy for regular expressions and windows paths!
'
R"
another raw string
" --
raw strings cannot end with a \
ur'
a
unicode
raw string
'
UR"
another raw
unicode
"
Use
\
at end of line to continue a string on next line.
Adjacent strings are concatened, e.g.
'Monty ' 'Python'
is the same as
'Monty Python'
.
u'hello' + ' world'
>
u'hello world'
(coerced to unicode)
String Literal Escapes
Escape
Meaning
\
newline
Ignored (escape newline)
\\
Backslash (\)
\e
Escape (ESC)
\v
Vertical Tab (VT)
Page 4 of 50
Python 2.6 Quick Reference
\'
Single quote (')
\f
Formfeed (FF)
\
ooo
char with octal value
ooo
\"
Double quote (")
\n
Linefeed (LF)
\a
Bell (BEL)
\r
Carriage Return (CR)
\x
hh
char with hex value
hh
\b
Backspace (BS)
\t
Horizontal Tab (TAB)
\u
xxxx
Character with 16bit hex value
xxxx
(unicode only)
\U
xxxxxxxx
Character with 32bit hex value
xxxxxxxx
(unicode only)
\N{
name
}
Character named in the Unicode database (unicode only), e.g.
u'\N{Greek Small Letter
Pi}'
<=>
u'\u03c0'.
(Conversely, in module unicodedata,
unicodedata.name(u'\u03c0') == 'GREEK SMALL
LETTER PI'
)
\
AnyOtherChar
left asis, including the backslash, e.g.
str('\z') == '\\z'
NUL byte (
\000
) is
not
an endofstring marker; NULs may be embedded in strings.
Strings (and tuples) are
immutable
: they cannot be modified.
Boolean constants (since 2.2.1)
True
False
In 2.2.1, True and False are integers 1 and 0. Since 2.3, they are of new type
bool
.
Numbers
Decimal integer
:
1234, 1234567890546378940
L
(or
l
)
Binary
integer:
0b
10,
0B
10,
0b
10101010101010101010101010101010L
(begins with a
0b
or
0B
)
Octal
integer:
0
177,
0o
177,
0O
177,
0
177777777777777777L
(begins with a
0
,
0o
, or
0O
)
Hex
integer:
0x
FF,
0X
FFFFffffFFFFFFFFFFL
(begins with
0x
or
0X
)
Long
integer (unlimited precision):
1234567890123456
L
(ends with
L
or
l
) or
long(
1234
)
Float
(double precision):
3
.
14
e-10
, .001, 10., 1E3
Complex
:
1
J
, 2
+
3
J
, 4
+
5
j
(ends with
J
or
j
,
+
separates (float) real and imaginary parts)
Integers and long integers are
unified
starting from release 2.2 (the
L
suffix is no longer required)
Sequences
Strings
(types
str
and
unicode
) of length 0, 1, 2 (see
above
)
'', '1', "12", 'hello\n'
Tuples
(type
tuple
) of length 0, 1, 2, etc:
()
(1
,
) (1,2) # parentheses are optional if len > 0
Lists
(type
list
) of length 0, 1, 2, etc:
[]
[1] [1,2]
Indexing is
0
based. Negative indices (usually) mean count backwards from end of sequence.
Sequence
slicing [
starting-at-index
:
but-less-than-index
[ : step]
]
. Start defaults to 0, end to len(sequence),
step to 1.
a = (0,1,2,3,4,5,6,7)
a[3] == 3
a[-1] == 7
a[2:4] == (2, 3)
a[1:] == (1, 2, 3, 4, 5, 6, 7)
a[:3] == (0, 1, 2)
a[:] == (0,1,2,3,4,5,6,7) # makes a
copy
of the sequence.
a[::2] == (0, 2, 4, 6) # Only even numbers.
a[::-1] = (7, 6, 5, 4, 3 , 2, 1, 0) # Reverse order.
Dictionaries (Mappings)
Page 5 of 50
Plik z chomika:
Pinus000
Inne pliki z tego folderu:
A Byte of Python, v1.20 (for Python 2.x) (2005).pdf
(337 KB)
A Byte of Python, v1.92 (for Python 3.0) (2009).pdf
(608 KB)
A Learner's Guide to Programming Using the Python Language (2009).pdf
(17233 KB)
A Primer on Scientific Programming with Python (2009).pdf
(6983 KB)
Beginning Game Development with Python and Pygame - From Novice to Professional (2007).pdf
(7814 KB)
Inne foldery tego chomika:
-- ▣▣▣ ELEKTRONIKA ▣▣ ▬▬▬▬▬▬▬▬▬▬▬▬▬
Pliki dostępne do 01.06.2025
Pliki dostępne do 08.07.2024
Pliki dostępne do 19.01.2025
►Kurs Java
Zgłoś jeśli
naruszono regulamin