Python Quick Reference
This quick reference provides an overview of the primary Python constructs used in this text. It is not a detailed reference but rather a compendium of tables and syntax. These are described in more detail within the chapters. In addition, more detailed documentation can be found at https://docs.python.org/
The words shown in TABLE B.1 are reserved by Python. You should not use any of these words as identifiers in your program. If you do, you will get a SyntaxError
.
TABLE B.1 Python’s Reserved Words |
---|
Python has three numeric data types:
▶ Integers
▶ Floating-point numbers
▶ Complex numbers
TABLE B.2 shows the most common operators for numeric data types.
TABLE B.2 Arithmetic Operators in Python |
||
---|---|---|
Operation Name |
Operator |
Explanation |
Addition |
|
Calculate the sum of two values. |
Subtraction |
|
Calculate the difference between two values. |
Multiplication |
|
Calculate the product of two values. |
Division |
|
Calculate the quotient of two values. |
Integer division |
|
Calculate the integer quotient of two integers. |
Remainder |
|
Find the remainder after performing a division. |
Exponentiation |
|
Raise a number to a power. Example: |
Python has a number of functions that can be called without an object reference. TABLE B.3 shows some common built-in functions.
TABLE B.3 Built-in Functions |
|
---|---|
|
Returns the character represented by the Unicode value |
|
Returns the list of names defined in the current local scope. |
|
Converts the number or string to a floating-point number. |
|
Returns documentation on |
|
Outputs the prompt, then reads a line and returns it as a string. |
|
Returns |
|
Converts the number or string to an integer. |
|
Returns the number of elements in |
|
Creates a list from the elements in |
|
Returns the maximum item in the |
|
Returns the minimum item in the |
|
Returns the next item from the iterator. |
|
Opens the file named |
|
Returns the Unicode value of a single-character string. |
|
Outputs each value separated by a space by default, ending with a line separator by default. |
|
Returns |
|
Function decorator that converts the method to a static method. |
|
Converts a number to a string. |
|
Returns the sum of the items in a numeric sequence. |
|
Call the superclass version of a method. |
Python has three sequential data types: strings, lists, and tuples. TABLE B.4 summarizes the operators that apply to all sequences.
TABLE B.4 Operations on Any Sequence in Python |
||
---|---|---|
Operation Name |
Operator |
Explanation |
Indexing |
|
Access an element of a sequence. |
Concatenation |
|
Combine sequences together. |
Repetition |
|
Concatenate a repeated number of times. |
Membership |
|
Ask whether an item is in a sequence. |
Membership |
|
Ask whether an item is not in a sequence. |
Length |
|
Ask the number of items in the sequence. |
Slicing |
|
Extract a part of a sequence. |
Strings are immutable sequences of characters that are indexed by integers, starting at zero. To create string literals, you can enclose them in single, double, or triple quotes as follows:
TABLE B.5 summarizes the more useful string methods.
TABLE B.5 Summary of String Methods |
||
---|---|---|
Method |
Use |
Explanation |
|
|
Returns the string |
|
|
Returns the number of occurrences of |
|
|
Returns |
|
|
Returns |
|
|
Returns |
|
|
Returns |
|
|
Returns the index of the first occurrence of |
|
|
Returns the index of the last occurrence of |
|
|
Returns the index of the first occurrence of |
|
|
Returns the index of the last occurrence of |
|
|
Replaces all occurrences of |
|
|
Returns a list of substrings, split at |
Lists are mutable sequences of references to any object. They are indexed by integers starting with zero. You can create a list as follows:
TABLE B.6 summarizes the most useful list methods.
TABLE B.6 Methods Provided by Lists in Python |
||
---|---|---|
Method Name |
Use |
Explanation |
|
|
Adds a new item to the end of a list. |
|
|
Inserts an item at the |
|
|
Removes and returns the last item in a list. |
|
|
Removes and returns the |
|
|
Modifies a list to be sorted from low to high. Optional |
|
|
Modifies a list to be in reverse order. |
|
|
Returns the index of the first occurrence of |
|
|
Returns the number of occurrences of |
|
|
Removes the first occurrence of |
You can convert sequences to lists using the list
function.
You can also create sequences using the following range
sequence.
range(stop)
Creates a sequence of numbers starting at 0 and going up to stop–1
range(start, stop)
Creates a sequence of numbers starting at start
and going up to stop–1
.
range(start, stop, step)
Creates a sequence of numbers starting at start
and going up to stop–1
counting by step
.
Tuples are immutable sequences of references to any object. You can create a tuple as follows:
Tuples support the same operators as lists, such as indexing and slicing. The main difference is that you cannot use an operator in a way that would modify the tuple. You may not use any of the list methods with a tuple.
The zip
function can be used to create a list of tuples from two or more sequences. The tuples consist of the i
th element from each sequence. For example:
A dictionary is a collection of pairs of key:objects
. The objects are referenced by their keys. The elements are maintained in the order in which they were added to the dictionary. You can create a Python dictionary as follows:
TABLE B.7 summarizes the Python dictionary methods
TABLE B.7 Methods Provided by Dictionaries in Python |
||
---|---|---|
Method Name |
Use |
Explanation |
|
|
Returns a |
|
|
Returns a |
|
|
Returns a |
|
|
Returns the value associated with key |
|
|
Returns the value associated with key |
|
|
If the key is not in the dictionary, insert the key with a value of |
|
|
Returns |
|
|
Returns |
|
|
Returns the value associated with |
|
|
Deletes all elements in the dictionary. |
|
|
The |
Files are sequences of characters that are stored on the disk. It is also useful to think of files as sequences of lines. TABLE B.8 summarizes File
methods.
TABLE B.8 Methods Provided by a File Object |
||
---|---|---|
Method Name |
Use |
Explanation |
|
|
Open a file called |
|
|
File use is complete. |
|
|
Add |
|
|
Reads and returns a string of |
|
|
Returns the next line of the file with all text up to and including the newline character. If |
|
|
Returns a list of |
The following program opens a file and reads it line by line, printing each line of the file.
It is also possible to read and print a file using a simple for
loop:
Python allows you to format strings using the string format
method. For example:
The format
method substitutes replacement fields for placeholders in the string using the formats specified by the placeholder. By default, the replacement fields are substituted in the same order as the placeholders. It is recommended, however, that each placeholder be identified by using its sequence number in curly braces {}
, as shown in {0}
, {1}
, and {2}
in the preceding code.
The format for a placeholder is:
TABLE B.9 show the various format characters that can be used to specify the type of the value.
TABLE B.9 Common Type Specifications |
||
---|---|---|
Type of Replacement Field |
Type Conversion Character |
Output Format |
String |
|
String. This is the default format. |
Integer |
|
Character. Converts an integer to its Unicode equivalent. |
|
Decimal integer. This is the default. |
|
|
Number. Same as decimal integer. |
|
Floating-point |
|
Scientific notation with a default precision of 6, as |
|
Fixed-point with default precision of 6, as |
|
|
General format. Uses scientific or fixed-point depending on the magnitude of the number. |
|
|
Same as |
|
|
Percentage. Multiplies the number by 100, then displays as |
TABLE B.10 show the various format characters that can be used to specify alignment, width, and precision for the value.
TABLE B.10 Common Format Modifiers |
||
---|---|---|
Modifier Type |
Modifier Character |
Output Format |
Alignment |
|
Left-align the value in its space. This is the default for strings. |
|
Right-align the value in its space. This is the default for numbers. |
|
|
Center the value within its space. |
|
Width |
|
The value will use the space of |
Precision |
|
Display |
The for
statement allows you to easily iterate over any collection of data using the following form:
The next three examples show you how to iterate over strings, lists, and tuples.
In this example, the variable i
will be bound to a new integer created by the range
function each time through the loop:
In this example, the loop variable i
will be bound to the next element in the list each time through the loop:
In this example, the loop variable ch
is bound to each character of the string:
It is also possible to iterate over a dictionary. The following examples show you two common patterns. In this case, the loop variable i
is bound to each key contained in the dictionary myDictionary
and prints the value associated with each key.
It is also possible to iterate over keys and values simultaneously using the following code:
In this example, the key–value pairs are pulled out of the dictionary ahead of time using the items
method.
while
The while
loop is an indefinite loop. It will continue to perform the statements in the body of the loop until the condition becomes False
. If the condition is never False
, then the loop is an infinite loop and will continue forever.
List comprehensions allow you to create lists by embedding a for
loop in a list creation expression. It is more convenient than writing a for
loop and using the append
method. Here is the general format for a list comprehension:
The if
statement is optional and only one for
loop is required. Here are some examples of simple list comprehensions:
A simple Boolean expression can be constructed using any of the relational operators shown in TABLE B.11.
TABLE B.11 Relational Operators and Their Meaning |
|
---|---|
Relational Operator |
Meaning |
|
Less than |
|
Less than or equal to |
|
Greater than |
|
Greater than or equal to |
|
Equal |
|
Not equal |
Multiple Boolean expressions can be joined using the logical operators and
, or
, and not
as shown in TABLE B.12. In this table, x and y are True
or False
.
TABLE B.12 Logical Operator Behavior |
|
---|---|
|
If |
|
If |
|
If |
elif
TABLE B.13 summarizes the main functions from the math
module used in this text.
TABLE B.13 Simple Math Functions |
||
---|---|---|
Method Name |
Use |
Explanation |
|
|
Returns the cosine of |
|
|
Returns the sine of |
|
|
Returns the tangent of |
|
|
Returns the Euclidean distance between 2 points, |
|
|
Converts |
|
|
Converts |
|
|
Returns the square root of |
TABLE B.14 summarizes the main functions from the random
module used in this text.
TABLE B.14 Random Number Generation |
||
---|---|---|
Method Name |
Use |
Explanation |
|
|
Returns a random number between 0.0 and 1.0. |
|
|
Returns a random number in the range 1, 3, including the endpoints. |
|
|
Returns a random number in the range 0, 3. Uses the same syntax as the |
TABLE B.15 summarizes some useful functions of the statistics
module.
TABLE B.15 Some Useful Functions of the |
|
---|---|
Method |
Explanation |
|
Returns the average of the data values. |
|
Returns the middle value of ordered numeric data. If the number of data items is even, return the average of the two middle values. |
|
Returns a list containing the values that appear most often. |
|
Returns the value that appears most often. If more than one value appears with the same highest frequency, raises a |
|
Returns the standard deviation. |
|
Returns the standard deviation, given the mean. |
TABLE B.16 summarizes the reader
function of the csv
module for reading .CSV
files and the next
function, which can be used with any iterator.
TABLE B.16 Useful Functions for Reading a |
|
---|---|
Method |
Explanation |
|
Returns an iterator object for moving through the rows of a . |
|
Returns the next row from the iterator. |
TABLE B.17 summarizes the urlopen
function of the urllib.request
module for opening a website address.
TABLE B.17 The |
|
---|---|
Method |
Explanation |
|
Opens a web address and returns a file handle. Raises a |
TABLE B.18 summarizes the loads
function of the json
module for converting JSON data to Python data formats.
TABLE B.18 The |
|
---|---|
Method |
Explanation |
|
Converts JSON objects to Python objects. JSON objects are translated to Python dictionaries; JSON arrays are translated to Python lists; and JSON data types are translated to Python data types. |
TABLE B.19 shows the abstract base class, ABC
, and TABLE B.20 shows the decorator used to specify that a method in an abstract class is itself abstract.
TABLE B.19 The |
|
---|---|
Class |
Explanation |
|
Abstract base class for convenience in defining an abstract class. The abstract class specifies |
TABLE B.20 The |
|
---|---|
Decorator |
Explanation |
|
Decorator that converts a method to an abstract method. |
The threading
module provides support for defining a multithreaded application. A multithreaded application needs to perform these three actions:
The class should inherit from the Thread
class. Ex: class MyApp(Thread)
The class should define a run
method that contains the code for the thread to execute.
The class should call the start
method. This will create a Thread
and call the run
method.
TABLE B.21 shows the run
and start
methods.
TABLE B.21 The |
|
---|---|
Method |
Description |
|
The method that contains the code to do the work of the thread. The subclass provides its own version of this method. |
|
Creates the thread and calls the thread’s |
The following is a list of some simple regular expression patterns:
|
Match any single character. |
|
Match |
|
Match any characters other than |
|
Match one or more occurrences of the characters |
|
Match zero or more occurrences of the characters |
(regex) |
Create a capture group. |
|
Apply patterns to end of string. |
TABLE B.22 summarizes the main regular expression functions in the re
module.
TABLE B.22 Regular Expression Module Functions |
||
---|---|---|
Method Name |
Use |
Explanation |
|
|
Matches any string that starts with |
|
|
Returns |
|
|
Returns |
|
|
Returns a list of all capture groups matched. |
|
|
Returns a single capture group at index 2. |
The del
statement is used to delete objects, such as variables, functions, and items in mutable sequences.
Deleting a function:
Deleting an object:
Deleting a list item:
Deleting a dictionary item:
Learning how to read and understand error messages can save a lot of time and trouble once you know what to look for.
One of the most common errors is the syntax error, which indicates that you have written a line of code that does not follow the rules of Python’s grammar. It is the equivalent of not ending a sentence with a period or forgetting to capitalize the first word of a sentence. Here is an example of a syntax error that is due to a missing colon (:
) at the end of the line def foo(x, y)
. It is also very common to get a syntax error like this when you are using an if
statement.
Another common error is to use a variable that has not yet been assigned a value. The following example shows the use of the variable spam
when spam
has no value. Note that this error message starts with the word Traceback
, which can help you pinpoint the line and the function where an error occurs. The traceback is followed by the error message itself, which says that a NameError
occurred. This message tells you that 'spam'
is undefined. Because the only way to define a variable in Python is to assign a value to it, this message should help you realize that you need to assign a value to spam
before using it in an expression.
Let’s look at another example of a traceback using a simple Python program we have saved in the file test.py
(LISTING B.1).
When we run this program we get the following output:
The first line of the traceback points to line 11 of the file test.py
, where main()
is called. The next line of the file points to line 8, where foo()
is called. The last line points to line 3, where we find the expression b = a + spam
. Once again Python tells us that spam
is not defined, and it gives us exactly the line that contains the error.
When working with a mixture of strings and numeric data types, you might try to “add” two incompatible things together. The next example shows an expression that tries to add a string and an integer. Python does not know whether it should convert '2'
to an integer and add two integers, or convert 2
to a string and concatenate two strings. Thus, it will give you this error message:
Here is another situation where Python cannot figure out what to add:
In this case, the statement a = 3 + bar
is missing the parentheses after the function named bar
. Even though bar
does not require any parameters, Python does not know that it should call the function without the “call operators” ()
.
Here is an example of using the call operators on an object that is not a function:
The next error is fairly easy to recognize, but it happens commonly:
Finally, here is an example of the error message you get when you attempt to iterate over something that is not a sequence. In this case, d
is an integer rather than a string, list, tuple, dictionary, or file.
18.116.42.9