This is a minimal introduction to Python, based on my web tutorial, “Instant Python.” It targets programmers who already know a language or two but who want to get up to speed with Python. For information on downloading and executing the Python interpreter, see Chapter 1 .
To get a basic feel for the Python language, think of it as pseudocode, because that’s pretty close to the truth. Variables don’t have types, so you don’t need to declare them. They appear when you assign to them and disappear when you don’t use them anymore. Assignment is done with the = operator, like this:
x = 42
Note that equality is tested by the == operator . You can assign several variables at once, like this:
x,y,z = 1,2,3
first, second = second, first
a = b = 123
Blocks are indicated through indentation and only through indentation. (No begin / end or braces.) The following are some common control structures :
if x < 5 or (x > 10 and x < 20):
print("The value is OK.")
if x < 5 or 10 < x < 20:
print("The value is OK.")
for i in [1, 2, 3, 4, 5]:
print("This is iteration number", i)
x = 10
while x >= 0:
print("x is still not negative.")
x = x - 1
The first two examples are equivalent.
The index variable given in the for loop iterates through the elements of a list 1 (written with brackets, as in the example). To make an “ordinary” for loop (that is, a counting loop), use the built-in function range .
# Print out the values from 0 to 99, inclusive
for value in range(100):
print(value)
The line beginning with # is a comment and is ignored by the interpreter.
Now you know enough (in theory) to implement any algorithm in Python. Let’s add some basicuser interaction . To get input from the user (from a text prompt), use the built-in function input .
x = float(input("Please enter a number:"))
print("The square of that number is", x * x)
The input function displays the (optional) prompt given and lets the user enter a string. In this case, we were expecting a number and so converted the input to a floating-point number using float .
So, you have control structures, input, and output covered—now you need some snazzy data structures. The most important ones are lists and dictionaries . Lists are written with brackets and can (naturally) be nested.
name = ["Cleese", "John"]
x = [[1, 2, 3], [y, z], [[[]]]]
One of the nice things about lists is that you can access their elements separately or in groups, through indexing and slicing . Indexing is done (as in many other languages) by writing the index in brackets after the list. (Note that the first element has index 0.)
print(name[1], name[0]) # Prints "John Cleese"
name[0] = "Smith"
Slicing is almost like indexing, except that you indicate both the start and stop index of the result, with a colon ( : ) separating them.
x = ["SPAM", "SPAM", "SPAM", "SPAM", "SPAM", "eggs", "and", "SPAM"]
print(x[5:7]) # Prints the list ["eggs", "and"]
Notice that the end is noninclusive. If one of the indices is dropped, it is assumed that you want everything in that direction. In other words, the slice x[:3] means “every element from the beginning of x up to element 3, noninclusive” (well, element 3 is actually the fourth element, because the counting starts at 0). The slice x[3:] would, on the other hand, mean “every element in x , starting at element 3 (inclusive) up to, and including, the last one.” For really interesting results, you can use negative numbers, too: x[-3] is the third element from the end of the list.
Now then, what about dictionaries? To put it simply, they are like lists, except that their contents aren’t ordered. How do you index them then? Well, every element has a key , or a name , which is used to look up the element, just as in a real dictionary. The following example demonstrates the syntax used to create dictionaries :
phone = {"Alice" : 23452532, "Boris" : 252336,
"Clarice" : 2352525, "Doris" : 23624643 }
person = {'first name': "Robin", 'last name': "Hood",
'occupation': "Scoundrel" }
Now, to get person ’s occupation, you use the expression person["occupation"] . If you wanted to change the person’s last name, you could write this:
person['last name'] = "of Locksley"
Simple, isn’t it? Like lists, dictionaries can hold other dictionaries, or lists, for that matter. And naturally, lists can hold dictionaries, too. That way, you can easily make some quite advanced data structures.
Our next step is abstraction . You want to give a name to a piece of code and call it with a couple of parameters. In other words, you want to define a function(also called a procedure ). That’s easy. Use the keyword def , as follows:
def square(x):
return x * x
print(square(2)) # Prints out 4
The return statement is used to return a value from the function.
When you pass a parameter to a function, you bind the parameter to the value, thus creating a new reference. This means that you can modify the original value directly inside the function, but if you make the parameter name refer to something else (rebind it), that change won’t affect the original. This works just like in Java, for example. Let’s take a look at an example:
def change(x):
x[1] = 4
y = [1, 2, 3]
change(y)
print(y) # Prints out [1,4,3]
As you can see, the original list is passed in, and if the function modifies it, these modifications carry over to the place where the function was called. Note the behavior in the following example, however, where the function body rebinds the parameter:
def nochange(x):
x = 0
y = 1
nochange(y)
print(y) # Prints out 1
Why doesn’t y change now? Because you don’t change the value ! The value that is passed in is the number 1, and you can’t change a number in the same way that you change a list. The number 1 is (and will always be) the number 1. What the example does change is what the parameter x refers to , and this does not carry over to the calling environment.
Python has all kinds of nifty things such as named arguments and default arguments and can handle a variable number of arguments to a single function. For more information about this, see Chapter 6 .
If you know how to use functions in general, what I’ve told you so far is basically what you need to know about them in Python.
It might be useful to know, however, that functions are values in Python. So if you have a function such as square , you could do something like the following:
queeble = square
print(queeble(2)) # Prints out 4
To call a function without arguments, you must remember to write doit() and not doit . The latter, as shown, only returns the function itself, as a value. This goes for methods in objects, too. Methods are described in the next section.
I assume you know how object-oriented programming works. Otherwise, this section might not make much sense. No problem—start playing without the objects, or check out Chapter 7 .
In Python, you define classes with the (surprise!) class keyword, as follows:
class Basket:
# Always remember the *self* argument
def __ init__(self, contents=None):
self.contents = contents or []
def add(self, element):
self.contents.append(element)
def print_me(self):
result = ""
for element in self.contents:
result = result + " " + repr(element)
print("Contains:", result)
Several things are worth noting in this example.
Methods are called like this: object.method(arg1, arg2) .
Some arguments can be optional and given a default value (as mentioned in the previous section on functions). This is done by writing the definition like this:
def spam(age=32): ...
Here, spam can be called with one or zero parameters. If it’s called without any parameters, age will have the default value of 32.
repr converts an object to its string representation. (So if element contains the number 1, then repr(element) is the same as "1" , whereas 'element' is a literal string.)
No methods or member variables (attributes) are protected (or private or the like) in Python. Encapsulation is pretty much a matter of programming style. (If you really need it, there are naming conventions that will allow some privacy, such as prefixing a name with a single or double underscore.)
Now, about that short-circuit logic . . .
All values in Python can be used as logic values. Some of the more empty ones (such as False , [] , 0 , "" , and None ) represent logical falsity; most other values (such as True , [0] , 1 , and "Hello, world" ) represent logical truth.
Logical expressions such as a and b are evaluated like this:
Check if a is true.
If it is not , then simply return it.
If it is , then simply return b (which will represent the truth value of the expression).
The corresponding logic for a or b is this:
If a is true, then return it.
If it isn’t, then return b .
This short-circuit mechanism enables you to use and and or like the Boolean operators they are supposed to implement, but it also enables you to write short and sweet little conditional expressions. For example, this statement:
if a:
print(a)
else:
print(b)
could instead be written like this:
print(a or b)
Actually, this is somewhat of a Python idiom, so you might as well get used to it.
Python also has also actual conditional expressions , so you can write this:
print(a if a else b)
The Basket constructor ( Basket.__init__ ) in the previous example uses this strategy in handling default parameters. The argument contents has a default value of None (which is, among other things, false); therefore, to check if it had a value, you could write this:
if contents:
self.contents = contents
else:
self.contents = []
Instead, the constructor uses this simple statement:
self.contents = contents or []
Why don’t you give it the default value of [] in the first place? Because of the way Python works, this would give all the Basket instances the same empty list as default contents. As soon as one of them started to fill up, they all would contain the same elements, and the default would not be empty anymore. To learn more about this, see the discussion about the difference between identity and equality in Chapter 5 .
When using None as a placeholder as done in the Basket.__init__ method, using contents is None as the condition is safer than simply checking the argument’s Boolean value. This will allow you to pass in a false value such as an empty list of your own (to which you could keep a reference outside the object).
If you would like to use an empty list as the default value, you can avoid the problem of sharing this among instances by doing the following:
def __init__(self, contents=[]):
self.contents = contents[:]
Can you guess how this works? Instead of using the same empty list everywhere, you use the expression contents[:] to make a copy. (You simply slice the entire thing.)
So, to actually make a Basket and to use it (to call some methods on it), you would do something like this:
b = Basket(['apple', 'orange'])
b.add("lemon")
b.print_me()
This would print out the contents of the Basket : an apple, an orange, and a lemon.
There are magic methods other than __init__ . One such method is __str__ , which defines how the object wants to look if it is treated like a string. You could use this in the basket instead of print_me .
def __str__(self):
result = ""
for element in self.contents:
result = result + " " + repr(element)
return "Contains: " + result
Now, if you wanted to print the basket b , you could just use this:
print(b)
Cool, huh?
Subclassing works like this:
class SpamBasket(Basket):
# ...
Python allows multiple inheritance, so you can have several superclasses in the parentheses, separated by commas. Classes are instantiated like this: x = Basket() . Constructors are, as I said, made by defining the special member function __init__ .
Let’s say that SpamBasket had a constructor __init__(self, type) . Then you could make a spam basket like this: y = SpamBasket("apples") .
If in the constructor of SpamBasket , you needed to call the constructor of one or more superclasses, you could call it like this: Basket.__init__(self) . Note that in addition to supplying the ordinary parameters, you must explicitly supply self , because the superclass __init__ doesn’t know which instance it is dealing with. A better (and slightly more magical) alternative would be super().__init__() .
For more about the wonders of object-oriented programming in Python, see Chapter 7 .
Here, I’ll quickly review a few other useful things before ending this appendix. Most useful functions and classes are put in modules , which are really text files with the file name extension .py that contain Python code. You can import these and use them in your own programs. For example, to use the function sqrt from the standard module math , you can do either this:
import math
x = math.sqrt(y)
or this:
from math import sqrt
x = sqrt(y)
For more information on the standard library modules , see Chapter 10 .
All the code in the module/script is run when it is imported. If you want your program to be both an importable module and a runnable program, you might want to add something like this at the end of it.
if __name__ == "__main__": main()
This is a magic way of saying that if this module is run as an executable script (that is, it is not being imported into another script), then the function main should be called. Of course, you could do anything after the colon there.
And for those of you who want to make an executable script in UNIX, use the following first line to make it run by itself:
#!/usr/bin/env python
Finally, a brief mention of an important concept: exceptions. Some operations (such as dividing something by zero or reading from a nonexistent file) produce an error condition or exception . You can even make your own exceptions and raise them at the appropriate times.
If nothing is done about the exception, your program ends and prints out an error message. You can avoid this with a try / except statement, as in this example:
def safe_division(a, b):
try:
return a/b
except ZeroDivisionError: pass
ZeroDivisionError is a standard exception. In this case, you could have checked if b was zero, but in many cases, that strategy is not feasible. And besides, if you removed the try / except statement in safe_division , thereby making it a risky function to call (called something like unsafe_division ), you could still do the following:
try:
unsafe_division(a, b)
except ZeroDivisionError:
print("Something was divided by zero in unsafe_division")
In cases in which you typically would not have a specific problem but it might occur, using exceptions enables you to avoid costly testing and so forth.
Well, that’s it. Hope you learned something. Now go and play. And remember the Python motto of learning: use the source (which basically means read all the code you can get your hands on).
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.
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. 2
Type | Description | Syntax Samples |
---|---|---|
Integer | Numbers without a fractional part | 42 |
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' ' |
Operator | Description | Precedence |
---|---|---|
lambda | Lambda expression | 1 |
… if … else | Conditional expression | 2 |
or | Logical or | 3 |
and | Logical and | 4 |
not | Logical negation | 5 |
in | Membership test | 6 |
not in | Negative membership test | 6 |
is | Identity test | 6 |
is not | Negative identity test | 6 |
< | Less than | 6 |
> | Greater than | 6 |
<= | Less than or equal to | 6 |
>= | Greater than or equal to | 6 |
== | Equal to | 6 |
!= | Not equal to | 6 |
| | Bitwise or | 7 |
^ | Bitwise exclusive or | 8 |
& | Bitwise and | 9 |
<< | Left shift | 10 |
>> | Right shift | 10 |
+ | Addition | 11 |
- | Subtraction | 11 |
* | Multiplication | 12 |
@ | Matrix multiplication | 12 |
/ | Division | 12 |
// | Integer division | 12 |
% | Remainder | 12 |
+ | Unary identity | 13 |
- | Unary negation | 13 |
∼ | Bitwise complement | 13 |
** | Exponentiation | 14 |
x.attribute | Attribute reference | 15 |
x[index] | Item access | 15 |
x[index1:index2[:index3]] | Slicing | 15 |
f(args…) | Function call | 15 |
(…) | Parenthesized expression or tuple display | 16 |
[…] | List display | 16 |
{key:value, …} | Dictionary display | 16 |
Function | Description |
---|---|
abs(number) | Returns the absolute value of a number. |
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 . |
ascii(object) | Works like repr , but escapes non-ASCII characters. |
bin(integer) | Converts an integer to a binary literal, in the form of a string. |
bool(x) | Interprets x as a Boolean value, returning True or False . |
bytearray([string, [encoding[, errors]]]) | Creates a byte array, optionally from a given string, with the specified encoding and error handling. |
bytes([string, [encoding[, errors]]]) | Similar to bytearray , but returns an immutable bytes object. |
callable(object) | Checks whether an object is callable. |
chr(number) | Returns a character whose Unicode code point is the given number. |
classmethod(func) | Creates a class method from an instance method (see Chapter 7 ). |
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 . Can supply a keyword argument start , to start somewhere other than zero. |
eval(string[, globals[, locals]]) | Evaluates a string containing an expression, optionally in a given global and local scope. |
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. |
format(value[, format_spec]) | Returns a formatted version of the given value, in the form of a string. The specification works the same way as the format string method. |
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]) | Returns data input by the user as a string, optionally using a given prompt. |
int(object[, radix]) | Converts a string (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). |
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. |
next(iterator[, default]) | Returns the value of iterator.__next__() , optionally providing a default if the iterator is exhausted. |
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]]) | Opens a file and returns a file object. (Has additional optional arguments, e.g., for encoding and error handling.) |
ord(char) | Returns the Unicode code point of a single character. |
pow(x, y[, z]) | Returns x to the power of y , optionally modulo z . |
print(x, …) | Print out a line containing zero or more arguments to standard output, separated by spaces. This behavior may be adjusted with the keyword arguments sep , end , file , and flush . |
property([fget[, fset[, fdel[, doc]]]]) | Creates a property from a set of accessors (see Chapter 9 ). |
range([start, ]stop[, step]) | Returns a numeric range (a form of sequence) with the given start (inclusive, default 0), stop (exclusive), and step (default 1). |
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). For detailed rounding rules, consult the official documentation. |
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 a proxy that delegates method calls to the superclass. |
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. |
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). |
zip(sequence1, …) | Returns an iterator 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. |
Method | Description |
---|---|
aList.append(obj) | Equivalent to aList[len(aList):len(aList)] = [obj] . |
aList.clear() | Removes all elements from aList . |
aList.count(obj) | Returns the number of indices i for which aList[i] == obj . |
aList.copy() | Returns a copy of aList . Note that this is a shallow copy, so the elements are not copied. |
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). |
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.items() | Returns an iterator (actually, a view ) of (key, value) pairs representing the items of aDict . |
aDict.iterkeys() | Returns an iterable object over the keys of aDict . |
aDict.keys() | Returns an iterator (view) 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). It can also be called with arguments similar to the dictionary constructor, aDict . |
aDict.values() | Returns an iterator (view) of the values in aDict (possibly containing duplicates). |
Method | Description |
---|---|
string.capitalize() | Returns a copy of the string in which the first character is capitalized. |
string.casefold() | Returns a string that has been normalized in a manner similar to simple lowercasing, more suitable for case-insensitive comparisons between Unicode strings. |
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.encode([encoding[, errors]]) | Returns the encoded version of the string using the given encoding, handling errors as specified by errors ( 'strict' , 'ignore' , or 'replace' , among other possible values). |
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.format(…) | Implements the standard Python string formatting. Brace-delimited fields in string are replaced by the corresponding arguments, and the result is returned. |
string.format_map(mapping) | Similar to using format with keyword arguments, except the arguments are provided as a mapping. |
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 alphanumeric characters. |
string.isalpha() | Checks whether the string consists of alphabetic characters. |
string.isdecimal() | Checks whether the string consists of decimal characters. |
string.isdigit() | Checks whether the string consists of digits. |
string.isidentifier() | Checks whether the string could be used as a Python identifier. |
string.islower() | Checks whether all the case-based characters (letters) of the string are lowercase. |
string.isnumeric() | Checks whether the string consists of numeric characters. |
string.isprintable() | Checks whether the string consists of printable characters. |
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). |
str.maketrans(x[, y[, z]]) | A static method on str . Constructs a translation table for translate , using a mapping x from characters or ordinals to Unicode ordinals (or None for deletion). Can also be called with two strings representing the from- and to-characters, and possibly a third, with characters to be deleted. |
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) | Returns a copy of the string in which all characters have been translated using table (constructed with maketrans ). |
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 (with any initial + or - moved to the beginning). |
This section gives you a quick summary of each of the statement types in Python.
Simple statements consist of a single (logical) line.
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 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 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
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 passstatement 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 delstatement 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 deleted only 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 returnstatement 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 yieldstatement 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 raisestatement 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 breakstatement 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 continuestatement 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 importstatement 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 globalstatement 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
This is similar to the globalstatement but refers to an outer scope of an inner function (a closure). That is, if you define a function inside another function and return it, this inner function may refer to—and modify—variables from the outer function, provided they are marked as nonlocal.
Example:
def makeinc():
count = 1
def inc():
nonlocal count
count += 1
return inc
Compound statements contain groups (blocks) of other statements.
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 whilestatement 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 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 trystatement 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 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.
Example:
with open("somefile.txt") as myfile:
dosomething(myfile)
# The file will have been closed here
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 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
Abstract base class
Abstraction
add function
Algorithm
and operator
Arcade game
goals
implementation
falling weights animation (weights.py)
game over screen
level cleared screen
main game module (squish.py)
Squish configuration file (config.py)
Squish game objects
Squish opening screen
squish.py file
steps
weights.py and weight.png
preparations
preparations weight and banana graphics
pygame module
pygame.display module
pygame.font module
pygame.image module
pygame.locals module
pygame.mouse module
pygame.sprite module
Arguments
print multiple
Assert statements
Assignment statement
augmented assignments
chained assignments
sequence unpacking
Asynchronous I/O
AttributeError
Attributes
Augmented assignments
Basket constructor
Binary search
Blocking network programming
Blocks
Boolean function
Boolean operators
Boolean values
Boost.Python
Break statement
Built-in exceptions
Built-in functions
Bulletin board
database creation
MySQL
PostgreSQL
SQLite
database structure
implementation
CGI scripts
Content-type string
core functionality
database-handling code figured out
edit script writing
formatting code
main page
main script writing
message composer
message viewer
save.cgi script
simple_main.cgi
structuring web programs
testing purposes
view.cgi script
requirements
tools
bytearray
Bytes
C API
Catching exceptions
Catching object
C extensions
Chained assignments
Character sets
ChatServer class
Class
abstract base
create new
definitions
namespace
subclass
superclass
Client/server pair
Client sockets
Close method
Closing files
cmath and complex numbers
Colon (:)
Comment
Common Gateway Interface (CGI)
cgi module
cgitb
file permissions
HTML forms
pound bang line
security risks
web server
Comparing incompatible types
Comparison operators
Compilation process
gcc
SWIG
Compiling extensions
Comprehensions
Conditional execution
elif clauses
else clauses
if statement
nesting blocks
Connections, Python DB API
Constructors
_ _init_ _
init method
overriding methods
parameters
super function
unbound superclass constructor
Content handler
Context managers
continue statement
Conversion specifiers
count method
CounterList class
ctypes module
Cursors, Python DB API
Cython
Data structure
Decorators
Default mode
Defaults
def statement
del statement
Dictionary
database
dict function
methods
clear
copy
fromkeys
get
items
keys
pop
popitem
setdefault
update
values
operations
string formatting
Docstring
doctest
Eight Queens problem
base case
conflicts
generators and backtracking
prettyprint
problem
recursive case
solutions
state representation
elif clauses
else clauses
Encapsulation
Environment variables
Equality operator
Error message
eval function
Event handling
except clause
Exceptions
built-in
catching
custom classes
definition
and functions
raise statement
with one block
zen of
exec function
Exploring modules
_ _all_ _ variable
dir function
documentation
help
Python interpreter
source code
Expression statements
Extensions
PyArg_ParseTuple
SWIG and Cython
Factorial (of number)
Fibonacci numbers
fibs function
Fictitious function
FileExistsError
fileinput module
File-like object
File(s)
closing files
context managers
file-like object
iterating over file contents
iterators
modes
modified text file
objects
opening files
Piping Output
random access
reading and writing
reading and writing lines
standard streams
somefile.txt
streams
File sharing, GUI
implementation
fetch method
finished GUI client (guiclient.py)
ListableNode
simple GUI client (simple_guiclient.py)
preparations
requirements
tools
File sharing, XML-RPC
client-server interaction
implementation
_broadcast method
client interface creation
command
file test.txt
new node implementation (server.py)
node controller interface (client.py)
raising exceptions
register_instance method
simple node
SimpleXMLRPCServer class
validating file names
peer-to-peer system
preparation
requirements
standard library modules
Filter class
filterwarnings function
Finally clause
Flask
Food Database Query program
Forking server
for loops
Formal parameters
for statement
Foundations of Python Network Programming
Friends and SocketServer
Functions
add
definition
document
eval
exec
fibs
filter
isinstance
map
return statement
store
Garbage collection
Generators
comprehension
definition
flatten generator
generator-function and generator-iterator
making
methods
recursive
simulating
Geometry manager
_ _getattr_ _ method
Global variables
Graphical user interfaces (GUIs)
elements
event handling
file sharing
initial exploration
layout
mechanisms
object-oriented design
text editor
Tkinter
Handlers
heapify function
heappop function
heapreplace function
Heaps
Hexadecimals and octals
Identity operator
if statement
Import something from module
import statement
in operator
IndexError
Infinite recursion
Inheritance
Input from user
Installation process
Interfaces
Interpreter
Introspection
IronPython
is operator
isinstance function
Item access
sequences and mappings
subclassing list, dict, and str
Iteration
iterating over file contents
fictitious function
fileinput
file iterators
one character (or byte) at time
one line at time
process
reading everything
numbered
parallel
reversed and sorted iteration
Iterators
list constructor
protocol
sequences making
_ _iter_ _ method
Jujitsu of programming
Jython
KeyError
Keyword arguments
Keyword parameters
Lambda expressions
Layout
Lazy evaluation
LinePlot class
LineReceiver class
Linux system
Lists
deleting elements
function
item assignments
method
append
clear
copy
count
extend
index
insert
pop
remove
reverse
sort
operations
slicing
Literal values
Local variables
Loops
break
continue
dictionary
else clauses
for loops
while loops
while True/break idiom
Markup system
handlers (handlers.py)
implementation
action method
constructing, rules and filters
filters
finding blocks of text
handler
handler superclass
Parser class
rules
script creation
web page generating
LATEX
main program (markup.py)
plain-text file
preparations
rules (rules.py)
tools
match function
Membership operator
Method resolution order (MRO)
Methods, attributes, functions, and
Minimal client
Minimal server
Modules
clientdb and billing code
conditional test code
define things
exploring
function defining
importlib module
interpreter
packages
packaging.python.org
problematic test code
program
PYTHONPATH environment variable
sys module
test code adding
Multiple inheritance
NameError
Namespace
Nesting
Nesting blocks
Networking modules
asynchronous I/O
blocking or synchronous network programming
CGI
forking and threading
friends
multiple connections
network-related modules in standard library
opening remote files
retrieving remote files
select and poll
selection
socket module
SocketServer framework
standard library
Twisted
urllib
URLs
Network News Transfer Protocol (NNTP)
News gathering agent
implementation
addSource and addDestination
getItems and receiveItems
methods
NewsAgent
newsagent2.py
news.html page
NewsItem
news page generated
nntplib
NNTP server
NNTPSource
PlainDestination
simple news-gathering agent
SimpleWebSource
preparations
servers
tools
urllib
NNTP
Nonsensical text
Numbered iteration
Numbers and expressions
NumPy module
Object-oriented programming
Object-relational mappers
Objects
encapsulation
inheritance
polymorphism
One character (or byte) at a time
One line at a time
open function
Operators
* and **
Boolean
comparison
equality
identity
membership
OSError
os Module
Overriding methods
Packages
Pack manager
Palindrome
Parallel iteration
Parameters
actual
change
collect
formal
keyword
positional
practice
style
wrapping
Parse method
pass statement
Piping Output
Plain-text markup
Playful Programming
configuration files
extracting constants
jujitsu
logging
prototyping
Polymorphism
definition
forms
interface
methods
term
popitem method
Positional parameters
Power
Pretty picture painting
crucial tool
file-handling and string-processing facilities
implementation
data getting
LinePlot class
PolyLine
prototype
ReportLab
sunspot graph
preparations
program
sunspot program (sunspots.py)
profile
Properties, magic methods
accessor methods
_ _getattr_ _and _ _setattr_ _
get_size and set_size methods
property function
Rectangle class
static methods and class methods
property function
Prototyping
_ _pycache_ _
PyChecker
PyCXX
py2exe extension
PyLint
PyPy
PySQLite
Python
abstraction
conditional expressions
control structures
DB API
connections
cursors
exceptions
global variables
Specification v2.0
SQLite and PySQLite
types and special values
dictionaries
exceptions
for loop iterates
function
input function
module/script
objects and stuff
== operator
standard library modules
user interaction
Python 3
Python Library Reference
raise statement
Random access
Random module
Reading and writing, files
Reading and writing lines
Rectangle class
Recursion
binary search
definition
factorial
infinite
power
Recursive generator
Reference counting
Regular expression
Remote editing, CGI
implementation
editor running
editor script writing
file name form, creation
prototype
save script writing
simple_edit.cgi script
simple web editor
preparations
requirements
tools
ReportLab program
Representational state transfer (REST)
Retrieving remote files
return statement
Reversed and sorted iteration
Rich Site Summary (RSS)
RPC
Rule superclass
Saving and executing program
command prompt
IDLE
making executable program
print statement
SAX programming
Scope, dictionary
Screen scraping
Beautiful Soup
HTMLParser
Tidy
urllib and re
XHTML
Select and poll, asynchronous I/O with
Sequence
adding
comparisons
indexing
len, min, and max
longer steps
membership
multiplying
nifty shortcut
none, empty lists and initialization
slicing
unpacking
Sequences and mappings protocol
arithmetic sequence
collections module
_ _delitem_ _(self, key)
_ _getitem_ _(self, key)
_ _len_ _ method
_ _len_ _(self)
requirements
_ _setitem_ _(self, key, value)
TypeError
Server socket
_ _setattr_ _ method
Sets module
Setuptools
Shape class
Short-circuit logic
Simple node implementation (simple_node.py)
SimpleWebSource
SIP
SOAP
Socket module
SocketServer framework
somefile.txt file
somescript.py
Sorting
SPAMFilters
SQLite
advantages
creating and populating tables
definition
and PySQLite
Python standard library
sample database application
searching and dealing
Standard library
deques
email headers
fileinput module
finding sender, email
group numbers and functions
heappush function
heaps
match objects and groups
os module
random
regular expression
alternatives and subpatterns
character sets
escaping special characters
optional and repeated subpatterns
string
wildcard
re module
functions
MatchObject
maxsplit argument
re.escape
re.split
re.sub
sets module
shelve and json
simple database application
standard modules
sys module
template system
time module
Standard streams
Statements
assert
assignment
augmented assignment
break
compound
continue
del
expressions
for statement
global
if statement
import
pass
raise
return
simple
try
while
with statement
yield
store function
Streams
String(s)
bytearray
bytes
concatenating strings
conversions
conversion specifiers
double quotes
escaping quotes
f-strings
keyword arguments
long string
methods
center
find
join
lower
replace
split
strip
title
translate
operations
operator
raw string
replacement field names
and sequence comparisons
signs, alignment, and zero-padding
single quotes
str and repr
unicode
width, precision, and thousands separators
Structure
Structure computer programs
Subclass
subprocess module
Sunspot graph
Superclass
Super function
SWIG
Synchronous network programming
SyntaxError
sys module
Test-driven programming
Testing
coverage
debugging
doctest
requirement specification
test-driven programming
unittest
Text Block generator
Threading server
threadsafety
thread-safety level
throw method
Tkinter
Traceback
Transmitting data
try/except statement
Tuples
Twisted framework
common GUI toolkits
downloading and installing
event-driven networking framework
in Python 2
server
Twisted Matrix Laboratories
TypeError
Unicode
Uniform Resource Locator (URL)
United States Department of Agriculture (USDA)
Unit tests (unittest)
profiler module
PyChecker
PyLint
Universal newline mode
UNIX system
urandom function
urllib module
urllib2 module
Usenet
ValueError
Variables
vars function
Virtual tea party
asyncore framework
chatserver.py
implementation
ChatServer class
ChatSession class
command interpretation
login and logout rooms
main chat room
rooms
simple chat server
preparations
tools
warnings module
Weave tool
Web framework
application
powers.py
Web services
REST
RPC
RSS
SOAP
while loops
while statement
while True/break idiom
with statement
XML
implementation
default handling
directories support
dispatcher mix-in class
event handlers
header and footer
HTML pages, creation
simple content handler
web site constructor (website.py)
page maker script
preparations
project goals
SAX mechanism
tools
web site represented
yield statement
Zen of exceptions
ZeroDivisionError
Zeroth character
zip function