images

This is not a full Python reference by far—you can find that in the standard Python documentation (http://python.org/doc/ref). Rather, this is a handy “cheat sheet” that can be useful for refreshing your memory as you start out programming in Python. See Appendix D for changes in the language that are introduced in version 3.0.

Expressions

This section summarizes Python expressions. Table B-1 lists the most important basic (literal) values in Python; Table B-2 lists the Python operators, along with their precedence (those with high precedence are evaluated before those with low precedence); Table B-3 describes some of the most important built-in functions; Tables B-4 through B-6 describe the list methods, dictionary methods, and string methods, respectively.

Table B-1. Basic (Literal) Values

Type Description Syntax Samples
Integer Numbers without a fractional part 42
Long integer Large integer numbers 42L
Float Numbers with a fractional part 42.5, 42.5e-2
Complex Sum of a real (integer or float) and imaginary number 38 + 4j, 42j
String An immutable sequence of characters 'foo', "bar", """baz""", r' '
Unicode An immutable sequence of Unicode characters u'foo', u"bar", u"""baz"""

Table B-2. Operators

Operator Description Precedence
lambda Lambda expression 1
or Logical or 2
and Logical and 3
not Logical negation 4
in Membership test 5
not in Negative membership test 5
is Identity test 6
is not Negative identity test 6
< Less than 7
> Greater than 7
<= Less than or equal to 7
>= Greater than or equal to 7
== Equal to 7
!= Not equal to 7
| Bitwise or 8
^ Bitwise exclusive or 9
& Bitwise and 10
<< Left shift 11
>> Right shift 11
+ Addition 12
- Subtraction 12
* Multiplication 13
/ Division 13
% Remainder 13
+ Unary identity 14
- Unary negation 14
~ Bitwise complement 15
** Exponentiation 16
x.attribute Attribute reference 17
x[index] Item access 18
x[index1:index2[:index3]] Slicing 19
f(args...) Function call 20
(...) Parenthesized expression or tuple display 21
[...] List display 22
{key:value, ...} Dictionary display 23
`expressions...` String conversion 24

Table B-3. Some Important Built-in Functions

Function Description
abs(number) Returns the absolute value of a number.
apply(function[, args[, kwds]]) Calls a given function, optionally with parameters.
all(iterable) Returns True if all the elements of iterable are true; otherwise, it returns False.
any(iterable) Returns True if any of the elements of iterable are true; otherwise, it returns False.
basestring() An abstract superclass for str and unicode, usable for type checking.
bool(object) Returns True or False, depending on the Boolean value of object.
callable(object) Checks whether an object is callable.
chr(number) Returns a character whose ASCII code is the given number.
classmethod(func) Creates a class method from an instance method (see Chapter 7).
cmp(x, y) Compares x and y. If x < y, it returns a negative number; if x > y, it returns a positive number; and if x == y, it returns zero.
complex(real[, imag]) Returns a complex number with the given real (and, optionally, imaginary) component.
delattr(object, name) Deletes the given attribute from the given object.
dict([mapping-or-sequence]) Constructs a dictionary, optionally from another mapping or a list of (key, value) pairs. May also be called with keyword arguments.
dir([object]) Lists (most of) the names in the currently visible scopes, or optionally (most of) the attributes of the given object.
divmod(a, b) Returns (a//b, a%b) (with some special rules for floats).
enumerate(iterable) Iterates over (index, item) pairs, for all items in iterable.
eval(string[, globals[, locals]]) Evaluates a string containing an expression, optionally in a given global and local scope.
execfile(file[, globals[, locals]]) Executes a Python file, optionally in a given global and local scope.
file(filename[, mode[, bufsize]]) Creates a file object with a given file name, optionally with a given mode and buffer size.
filter(function, sequence) Returns a list of the elements from the given sequence for which function returns true.
float(object) Converts a string or number to a float.
frozenset([iterable]) Creates a set that is immutable, which means it can be added to other sets.
getattr(object, name[, default]) Returns the value of the named attribute of the given object, optionally with a given default value.
globals() Returns a dictionary representing the current global scope.
hasattr(object, name) Checks whether the given object has the named attribute.
help([object]) Invokes the built-in help system, or prints a help message about the given object.
hex(number) Converts a number to a hexadecimal string.
id(object) Returns the unique ID for the given object.
input([prompt]) Equivalent to eval(raw_input(prompt)).
int(object[, radix]) Converts a string or number (optionally with a given radix) or number to an integer.
isinstance(object, classinfo) Checks whether the given object is an instance of the given classinfo value, which may be a class object, a type object, or a tuple of class and type objects.
issubclass(class1, class2) Checks whether class1 is a subclass of class2 (every class is a subclass of itself).
iter(object[, sentinel]) Returns an iterator object, which is object.__iter__(), an iterator constructed for iterating a sequence (if object supports __getitem__), or, if sentinel is supplied, an iterator that keeps calling object in each iteration until sentinel is returned.
len(object) Returns the length (number of items) of the given object.
list([sequence]) Constructs a list, optionally with the same items as the supplied sequence.
locals() Returns a dictionary representing the current local scope (do not modify this dictionary).
long(object[, radix]) Converts a string (optionally with a given radix) or number to a long integer.
map(function, sequence, ...) Creates a list consisting of the values returned by the given function when applying it to the items of the supplied sequence(s).
max(object1, [object2, ...]) If object1 is a nonempty sequence, the largest element is returned; otherwise, the largest of the supplied arguments (object1, object2, . . .) is returned.
min(object1, [object2, ...]) If object1 is a nonempty sequence, the smallest element is returned; otherwise, the smallest of the supplied arguments (object1, object2, . . .) is returned.
object() Returns an instance of object, the base class for all new style classes.
oct(number) Converts an integer number to an octal string.
open(filename[, mode[, bufsize]]) An alias for file (use open, not file, when opening files).
ord(char) Returns the ASCII value of a single character (a string or Unicode string of length 1).
pow(x, y[, z]) Returns x to the power of y, optionally modulo z.
property([fget[, fset[, fdel[, doc]]]]) Creates a property from a set of accessors (see Chapter 9).
range([start, ]stop[, step]) Returns a numeric range (as a list) with the given start (inclusive, default 0), stop (exclusive), and step (default 1).
raw_input([prompt]) Returns data input by the user as a string, optionally using a given prompt.
reduce(function, sequence[, initializer]) Applies the given function cumulatively to the items of the sequence, using the cumulative result as the first argument and the items as the second argument, optionally with a start value (initializer).
reload(module) Reloads an already loaded module and returns it.
repr(object) Returns a string representation of the object, often usable as an argument to eval.
reversed(sequence) Returns a reverse iterator over the sequence.
round(float[, n]) Rounds off the given float to n digits after the decimal point (default zero).
set([iterable]) Returns a set whose elements are taken from iterable (if given).
setattr(object, name, value) Sets the named attribute of the given object to the given value.
sorted(iterable[, cmp][, key][, reverse]) Returns a new sorted list from the items in iterable. Optional parameters are the same as for the list method sort.
staticmethod(func) Creates a static (class) method from an instance method (see Chapter 7).
str(object) Returns a nicely formatted string representation of the given object.
sum(seq[, start]) Returns the sum of a sequence of numbers, added to the optional parameter start (default 0).
super(type[, obj/type]) Returns the superclass of the given type (optionally instantiated).
tuple([sequence]) Constructs a tuple, optionally with the same items as the supplied sequence.
type(object) Returns the type of the given object.
type(name, bases, dict) Returns a new type object with the given name, bases, and scope.
unichr(number) The Unicode version of chr.
unicode(object[, encoding[, errors]]) Returns a Unicode encoding of the given object, possibly with a given encoding, and a given mode for handling errors ('strict', 'replace', or 'ignore'; 'strict' is the default).
vars([object]) Returns a dictionary representing the local scope, or a dictionary corresponding to the attributes of the given object (do not modify the returned dictionary, as the result of such a modification is not defined by the language reference).
xrange([start, ]stop[, step]) Similar to range, but the returned object uses less memory, and should be used only for iteration.
zip(sequence1, ...) Returns a list of tuples, where each tuple contains an item from each of the supplied sequences. The returned list has the same length as the shortest of the supplied sequences.

Table B-4. List Methods

Method Description
aList.append(obj) Equivalent to aList[len(aList):len(aList)] = [obj].
aList.count(obj) Returns the number of indices i for which alist[i] == obj.
aList.extend(sequence) Equivalent to aList[len(aList):len(aList)] = sequence.
aList.index(obj) Returns the smallest i for which aList[i] == obj (or raises a ValueError if no such i exists).
aList.insert(index, obj) Equivalent to aList[index:index] = [obj] if index >= 0; if index < 0, object is prepended to the list.
aList.pop([index]) Removes and returns the item with the given index (default –1).
aList.remove(obj) Equivalent to del aList[aList.index(obj)].
aList.reverse() Reverses the items of aList in place.
aList.sort([cmp][, key][, reverse]) Sorts the items of aList in place (stable sorting). Can be customized by supplying a comparison function, cmp; a key function, key, which will create the keys for the sorting); and a reverse flag (a Boolean value).

Table B-5. Dictionary Methods

Method Description
aDict.clear() Removes all the items of aDict.
aDict.copy() Returns a copy of aDict.
aDict.fromkeys(seq[, val]) Returns a dictionary with keys from seq and values set to val (default None). May be called directly on the dictionary type, dict, as a class method.
aDict.get(key[, default]) Returns aDict[key] if it exists; otherwise, it returns the given default value (default None).
aDict.has_key(key) Checks whether aDict has the given key.
aDict.items() Returns a list of (key, value) pairs representing the items of aDict.
aDict.iteritems() Returns an iterable object over the same (key, value) pairs as returned by aDict.items.
aDict.iterkeys() Returns an iterable object over the keys of aDict.
aDict.itervalues() Returns an iterable object over the values of aDict.
aDict.keys() Returns a list of the keys of aDict.
aDict.pop(key[, d]) Removes and returns the value corresponding to the given key, or the given default, d.
aDict.popitem() Removes an arbitrary item from aDict and returns it as a (key, value) pair.
aDict.setdefault(key[, default]) Returns aDict[key] if it exists; otherwise, it returns the given default value (default None) and binds aDict[key] to it.
aDict.update(other) For each item in other, adds the item to aDict (possibly overwriting existing items). Can also be called with arguments similar to the dictionary constructor, aDict.
aDict.values() Returns a list of the values in aDict (possibly containing duplicates).

Table B-6. String Methods

Method Description
string.capitalize() Returns a copy of the string in which the first character is capitalized.
string.center(width[, fillchar]) Returns a string of length max(len(string), width) in which a copy of string is centered, padded with fillchar (the default is space characters).
string.count(sub[, start[, end]]) Counts the occurrences of the substring sub, optionally restricting the search to string[start:end].
string.decode([encoding[, errors]]) Returns decoded version of the string using the given encoding, handling errors as specified by errors ('strict', 'ignore', or 'replace').
string.encode([encoding[, errors]]) Returns the encoded version of the string using the given encoding, handling errors as specified by errors ('strict', 'ignore', or 'replace').
string.endswith(suffix[, start[, end]]) Checks whether string ends with suffix, optionally restricting the matching with the given indices start and end.
string.expandtabs([tabsize]) Returns a copy of the string in which tab characters have been expanded using spaces, optionally using the given tabsize (default 8).
string.find(sub[, start[, end]]) Returns the first index where the substring sub is found, or −1 if no such index exists, optionally restricting the search to string[start:end].
string.index(sub[, start[, end]]) Returns the first index where the substring sub is found, or raises a ValueError if no such index exists, optionally restricting the search to string[start:end].
string.isalnum() Checks whether the string consists of alpha-numeric characters.
string.isalpha() Checks whether the string consists of alphabetic characters.
string.isdigit() Checks whether the string consists of digits.
string.islower() Checks whether all the case-based characters (letters) of the string are lowercase.
string.isspace() Checks whether the string consists of whitespace.
string.istitle() Checks whether all the case-based characters in the string following non-case–based letters are uppercase and all other case-based characters are lowercase.
string.isupper() Checks whether all the case-based characters of the string are uppercase.
string.join(sequence) Returns a string in which the string elements of sequence have been joined by string.
string.ljust(width[, fillchar]) Returns a string of length max(len(string), width) in which a copy of string is left-justified, padded with fillchar (the default is space characters).
string.lower() Returns a copy of the string in which all case-based characters have been lowercased.
string.lstrip([chars]) Returns a copy of the string in which all chars have been stripped from the beginning of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).
string.partition(sep) Searches for sep in the string and returns (head, sep, tail).
string.replace(old, new[, max]) Returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
string.rfind(sub[, start[, end]]) Returns the last index where the substring sub is found, or −1 if no such index exists, optionally restricting the search to string[start:end].
string.rindex(sub[, start[, end]]) Returns the last index where the substring sub is found, or raises a ValueError if no such index exists, optionally restricting the search to string[start:end].
string.rjust(width[, fillchar]) Returns a string of length max(len(string), width) in which a copy of string is right-justified, padded with fillchar (the default is space characters).
string.rpartition(sep) Same as partition, but searches from the right.
string.rstrip([chars]) Returns a copy of the string in which all chars have been stripped from the end of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).
string.rsplit([sep[, maxsplit]]) Same as split, but when using maxsplit, counts from right to left.
string.split([sep[, maxsplit]]) Returns a list of all the words in the string, using sep as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to maxsplit.
string.splitlines([keepends]) Returns a list with all the lines in string, optionally including the line breaks (if keepends is supplied and is true).
string.startswith(prefix[, start[, end]]) Checks whether string starts with prefix, optionally restricting the matching with the given indices start and end.
string.strip([chars]) Returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).
string.swapcase() Returns a copy of the string in which all the case-based characters have had their case swapped.
string.title() Returns a copy of the string in which all the words are capitalized.
string.translate(table[, deletechars]) Returns a copy of the string in which all characters have been translated using table (constructed with the maketrans function in the string module), optionally deleting all characters found in the string deletechars.
string.upper() Returns a copy of the string in which all the case-based characters have been uppercased.
string.zfill(width) Pads string on the left with zeros to fill width.

Statements

This section gives you a quick summary of each of the statement types in Python.

Simple Statements

Simple statements consist of a single (logical) line.

Expression Statements

Expressions can be statements on their own. This is especially useful if the expression is a function call or a documentation string.

Example:

"This module contains SPAM-related functions."
Assert Statements

Assert statements check whether a condition is true and raise an AssertionError (optionally with a supplied error message) if it isn’t.

Example:

assert age >= 12, 'Children under the age of 12 are not allowed'
Assignment Statements

Assignment statements bind variables to values. Multiple variables may be assigned to simultaneously (through sequence unpacking) and assignments may be chained.

Examples:

x = 42                   # Simple assignment
name, age = 'Gumby', 60  # Sequence unpacking
x = y = z = 10           # Chained assignments
Augmented Assignment Statements

Assignments may be augmented by operators. The operator will then be applied to the existing value of the variable and the new value, and the variable will be rebound to the result. If the original value is mutable, it may be modified instead (with the variable staying bound to the original).

Examples:

x *= 2                   # Doubles x
x += 5                   # Adds 5 to x
The pass Statement

The pass statement is a “no-op,” which does nothing. It is useful as a placeholder, or as the only statement in syntactically required blocks where you want no action to be performed.

Example:

try: x.name
except AttributeError: pass
else: print 'Hello', x.name
The del Statement

The del statement unbinds variables and attributes, and removes parts (positions, slices, or slots) from data structures (mappings or sequences). It cannot be used to delete values directly, because values are only deleted through garbage collection.

Examples:

del x                      # Unbinds a variable
del seq[42]                # Deletes a sequence element
del seq[42:]               # Deletes a sequence slice
del map['foo']             # Deletes a mapping item
The print Statement

The print statement writes one or more values (automatically formatted with str, separated by single spaces) to a given stream, with sys.stdout being the default. It adds a line break to the end of the written string unless the print statement ends with a comma.

Examples:

print 'Hello, world!'     # Writes 'Hello, world ' to sys.stdout
print 1, 2, 3             # Writes '1 2 3 ' to sys.stdout
print >> somefile, 'xyz'  # Writes 'xyz' to somefile
print 42,                 # Writes '42 ' to sys.stdout
The return Statement

The return statement halts the execution of a function and returns a value. If no value is supplied, None is returned.

Examples:

return                 # Returns None from the current function
return 42              # Returns 42 from the current function
return 1, 2, 3         # Returns (1, 2, 3) from the current function
The yield Statement

The yield statement temporarily halts the execution of a generator and yields a value. A generator is a form of iterator and can be used in for loops, among other things.

Example:

yield 42          # Returns 42 from the current function
The raise Statement

The raise statement raises an exception. It may be used without any arguments (inside an except clause, to re-raise the currently caught exception), with a subclass of Exception and an optional argument (in which case, an instance is constructed), or with an instance of a subclass of Exception.

Examples:

raise                    # May only be used inside except clauses
raise IndexError
raise IndexError, 'index out of bounds'
raise IndexError('index out of bounds')
The break Statement

The break statement ends the immediately enclosing loop statement (for or while) and continues execution immediately after that loop statement.

Example:

while True:
    line = file.readline()
    if not line: break
    print line
The continue Statement

The continue statement is similar to the break statement in that it halts the current iteration of the immediately enclosing loop, but instead of ending the loop completely, it continues execution at the beginning of the next iteration.

Example:

while True:
    line = file.readline()
    if not line: break
    if line.isspace(): continue
    print line
The import Statement

The import statement is used to import names (variables bound to functions, classes, or other values) from an external module. This also covers from __future__ import ... statements for features that will become standard in future versions of Python.

Examples:

import math
from math import sqrt
from math import sqrt as squareroot
from math import *
The global Statement

The global statement is used to mark a variable as global. It is used in functions to allow statements in the function body to rebind global variables. Using the global statement is generally considered poor style and should be avoided whenever possible.

Example:

count = 1
def inc():
    global count
    count += 1
The exec Statement

The exec statement is used to execute strings containing Python statements, optionally with a given global and local namespace (dictionaries).

Examples:

exec 'print "Hello, world!"'
exec 'x = 2' in myglobals, mylocals # ... where myglobals and mylocals are dicts

Compound Statements

Compound statements contain groups (blocks) of other statements.

The if Statement

The if statement is used for conditional execution, and it may include elif and else clauses.

Example:

if x < 10:
    print 'Less than ten'
elif 10 <= x < 20:
    print 'Less than twenty'
else:
    print 'Twenty or more'
The while Statement

The while statement is used for repeated execution (looping) while a given condition is true. It may include an else clause (which is executed if the loop finishes normally, without any break or return statements, for instance).

Example:

x = 1
while x < 100:
    x *= 2
print x
The for Statement

The for statement is used for repeated execution (looping) over the elements of sequences or other iterable objects (objects having an __iter__ method that returns an iterator). It may include an else clause (which is executed if the loop finishes normally, without any break or return statements, for instance).

Example:

for i in range(10, 0, -1):
    print i
print 'Ignition!'
The try Statement

The try statement is used to enclose pieces of code where one or more known exceptions may occur, and enables your program to trap these exceptions and perform exception-handling code if an exception is trapped. The try statement can combine several except clauses (handling exceptional circumstances) and finally clauses (executed no matter what; useful for cleanup).

Example:

try:
    1/0
except ZeroDivisionError:
    print "Can't divide anything by zero."
finally:
    print "Done trying to calculate 1/0"
The with Statement

The with statement is used to wrap a block of code using a so-called context manager, allowing the context manager to perform some setup and cleanup actions. For example, files can be used as context managers, and they will close themselves as part of the cleanup.

imagesNote  In Python 2.5, you need from __future__ import with_statement for the with statement to work as described.

Example:

with open("somefile.txt") as myfile:
    dosomething(myfile)
# The file will have been closed here
Function Definitions

Function definitions are used to create function objects and to bind global or local variables to these function objects.

Example:

def double(x):
    return x*2
Class Definitions

Class definitions are used to create class objects and to bind global or local variables to these class objects.

Example:

class Doubler:
    def __init__(self, value):
        self.value = value
    def double(self):
        self.value *= 2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset