Chapter Opener Photo

APPENDIX B

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/

B.1 Python Reserved Words

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

Image

B.2 Numeric Data Types

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: (x ** y) is equivalent to xy.

B.3 Built-in Functions

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

chr(num)

Returns the character represented by the Unicode value num.

dir()

Returns the list of names defined in the current local scope.

float(numOrString)

Converts the number or string to a floating-point number.

help(str)

Returns documentation on str.

input(prompt)

Outputs the prompt, then reads a line and returns it as a string.

isinstance(object, class)

Returns True if object is an instance of class; False if not.

int(numOrString)

Converts the number or string to an integer.

len(sequence)

Returns the number of elements in sequence.

list(sequence)

Creates a list from the elements in sequence.

max(sequence)

Returns the maximum item in the sequence.

min(sequence)

Returns the minimum item in the sequence.

next(iterator)

Returns the next item from the iterator.

open(filename, mode)

Opens the file named 'filename', mode can be 'r'(read), 'w'(write), or 'a'(append).

ord(ch)

Returns the Unicode value of a single-character string.

print( value1, …, separator=None,

end=endstring, file=None, flush=False)

Outputs each value separated by a space by default, ending with a line separator by default.

round(num, nDigits)

Returns num rounded to nDigits after the decimal point; if nDigits is not given, returns the nearest integer.

@staticmethod

Function decorator that converts the method to a static method.

str(num)

Converts a number to a string.

sum(sequence)

Returns the sum of the items in a numeric sequence.

super()

Call the superclass version of a method.

B.4 Sequence Operators

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

in

Ask whether an item is in a sequence.

Membership

not in

Ask whether an item is not in a sequence.

Length

len

Ask the number of items in the sequence.

Slicing

[ : ]

Extract a part of a sequence.

B.4.1 String

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:

Image

TABLE B.5 summarizes the more useful string methods.

TABLE B.5 Summary of String Methods

Method

Use

Explanation

center

aString.center(w)

Returns the string aString but surrounded by spaces to make the length of aString w characters long.

count

aString.count(item)

Returns the number of occurrences of item in aString.

ljust

aString.ljust(w)

Returns aString left-justified in a field of width w.

rjust

aString.rjust(w)

Returns aString right-justified in a field of width w.

upper

aString.upper()

Returns aString in all uppercase.

lower

aString.lower()

Returns aString in all lowercase.

index

aString.index(item)

Returns the index of the first occurrence of item in aString, or an error if not found.

rindex

aString.rindex(item)

Returns the index of the last occurrence of item in aString, or an error if not found.

find

aString.find(item)

Returns the index of the first occurrence of item in aString, or –1 if not found.

rfind

aString.rfind(item)

Returns the index of the last occurrence of item in aString, or –1 if not found.

replace

aString.replace(old, new)

Replaces all occurrences of old substring with new substring in aString.

split

aString.split(sChar)

Returns a list of substrings, split at sChar.

B.4.2 Lists

Lists are mutable sequences of references to any object. They are indexed by integers starting with zero. You can create a list as follows:

Image

TABLE B.6 summarizes the most useful list methods.

TABLE B.6 Methods Provided by Lists in Python

Method Name

Use

Explanation

append

aList.append(item)

Adds a new item to the end of a list.

insert

aList.insert(i, item)

Inserts an item at the ith position in a list.

pop

aList.pop()

Removes and returns the last item in a list.

pop

aList.pop(i)

Removes and returns the ith item in a list.

sort

aList.sort(key=None, reverse=False)

Modifies a list to be sorted from low to high. Optional key specifies a function to extract a field as the sort value. If reverse is True, the list is sorted from high to low.

reverse

aList.reverse()

Modifies a list to be in reverse order.

index

aList.index(item)

Returns the index of the first occurrence of item.

count

aList.count(item)

Returns the number of occurrences of item.

remove

aList.remove(item)

Removes the first occurrence of item.

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.

Image

B.4.3 Tuples

Tuples are immutable sequences of references to any object. You can create a tuple as follows:

Image

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 ith element from each sequence. For example:

Image

B.5 Dictionaries

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:

Image

TABLE B.7 summarizes the Python dictionary methods

TABLE B.7 Methods Provided by Dictionaries in Python

Method Name

Use

Explanation

keys

aDict.keys()

Returns a dict_keys object of keys in the dictionary.

values

aDict.values()

Returns a dict_values object of values in the dictionary.

items

aDict.items()

Returns a dict_items object of key–value tuples.

get

aDict.get(k)

Returns the value associated with key k; None otherwise.

get

aDict.get(k, alt)

Returns the value associated with key k; alt otherwise.

setdefault(key, default)

value = nDict.setdefault(

key,

defaultValue)

If the key is not in the dictionary, insert the key with a value of defaultValue and return defaultValue. If the key is in the dictionary, return the value for the key.

in

key in aDict

Returns True if key is in the dictionary; False otherwise.

not in

key not in aDict

Returns True if key is not in the dictionary; False otherwise.

index

aDict[key]

Returns the value associated with key.

clear()

aDict.clear()

Deletes all elements in the dictionary.

del

del aDict[key]

The del statement removes the entry from the dictionary.

B.6 Files

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 (filename, mode)

with open(filename,'r') as fileVar

Open a file called filename and use it for reading. This will return a reference (fileVar) to a file object. Other modes are 'w' for writing, and 'a' for appending to a file. Read ('r') is the default. With this use of open, the file is closed automatically when processing finishes.

close

fileVar.close()

File use is complete.

write

nChars = fileVar.write(aString)

Add aString to the end of the file. filevar must refer to a file that has been opened for writing. Returns the number of characters written.

read(n)

aString = fileVar.read(n)

Reads and returns a string of n characters, or the entire file as a single string if n is not provided.

readline(n)

aString = fileVar.readline(n)

Returns the next line of the file with all text up to and including the newline character. If n is provided as a parameter, then only n characters will be returned if the line is longer than n. Returns an empty string when the end of the file is reached.

readlines(n)

stringList = fileVar.readlines(n)

Returns a list of n strings, each representing a single line of the file including the terminating newline character. If n is not provided, then all lines of the file are returned.

The following program opens a file and reads it line by line, printing each line of the file.

Image

It is also possible to read and print a file using a simple for loop:

Image

B.7 Formatting Output

Python allows you to format strings using the string format method. For example:

Image

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:

Image

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

s

String. This is the default format.

Integer

c

Character. Converts an integer to its Unicode equivalent.

d

Decimal integer. This is the default.

n

Number. Same as decimal integer.

Floating-point

e or E

Scientific notation with a default precision of 6, as m.ddddde+/-xx or m.dddddE+/-xx.

f or F

Fixed-point with default precision of 6, as m.dddddd.

g

General format. Uses scientific or fixed-point depending on the magnitude of the number.

n

Same as g.

%

Percentage. Multiplies the number by 100, then displays as f format and appends a percent sign.

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

w

The value will use the space of w characters. The default is to use the minimum space required to display the value.

Precision

.n

Display n numbers after the decimal point.

B.8 Iteration

B.8.1 Simple Iteration over Collections of Data

The for statement allows you to easily iterate over any collection of data using the following form:

Image

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:

Image

In this example, the loop variable i will be bound to the next element in the list each time through the loop:

Image

In this example, the loop variable ch is bound to each character of the string:

Image

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.

Image

It is also possible to iterate over keys and values simultaneously using the following code:

Image

In this example, the key–value pairs are pulled out of the dictionary ahead of time using the items method.

B.8.2 Iteration with 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.

Image

B.8.3 List Comprehensions

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:

Image

The if statement is optional and only one for loop is required. Here are some examples of simple list comprehensions:

Image
Image

B.9 Boolean Expressions

B.9.1 Relational Operators

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

B.9.2 Compound Boolean Expressions

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

x and y

If x is False, return x; otherwise, return y.

x or y

If x is False, return y; otherwise, return x.

not x

If x is False, return True; otherwise, return False.

B.10 Selection

B.10.1 Binary Selection

Image

B.10.2 Unary Selection

Image

B.10.3 Nested Selection with elif

Image

B.11 Python Modules

B.11.1 Math

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

cos

math.cos(x)

Returns the cosine of x where x is in radians.

sin

math.sin(x)

Returns the sine of x where x is in radians.

tan

math.tan(x)

Returns the tangent of x where x is in radians.

dist

math.dist (p1, p2)

Returns the Euclidean distance between 2 points, p1 and p2, specified as a tuple.

degrees

math.degrees(r)

Converts r radians to degrees.

radians

math.radians(d)

Converts d degrees to radians.

sqrt

math.sqrt(x)

Returns the square root of x.

B.11.2 Random Numbers

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

random

random.random()

Returns a random number between 0.0 and 1.0.

randint

random.randint(1, 3)

Returns a random number in the range 1, 3, including the endpoints.

randrange

random.randrange(4)

Returns a random number in the range 0, 3. Uses the same syntax as the range function for specifying ranges of numbers.

B.11.3 Statistics

TABLE B.15 summarizes some useful functions of the statistics module.

TABLE B.15 Some Useful Functions of the statistics Module

Method

Explanation

mean(data)

Returns the average of the data values.

median(data)

Returns the middle value of ordered numeric data. If the number of data items is even, return the average of the two middle values.

multimode(data)

Returns a list containing the values that appear most often.

mode(data)

Returns the value that appears most often. If more than one value appears with the same highest frequency, raises a StatisticsError.

stdev(data)

Returns the standard deviation.

stdev(data, mean)

Returns the standard deviation, given the mean.

B.11.4 Reading CSV Files

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 .CSV File

Method

Explanation

reader(file)

Returns an iterator object for moving through the rows of a .CSV file. Each row is returned as a list of its fields.

next(iterator)

Returns the next row from the iterator.

B.11.5 Opening a URL

TABLE B.17 summarizes the urlopen function of the urllib.request module for opening a website address.

TABLE B.17 The urlopen Function in the urllib.request Module

Method

Explanation

urlopen(url)

Opens a web address and returns a file handle. Raises a URLError if unsuccessful.

B.11.6 Reading JSON Data

TABLE B.18 summarizes the loads function of the json module for converting JSON data to Python data formats.

TABLE B.18 The loads Function in the json Module

Method

Explanation

loads(jsonData)

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.

B.11.7 Abstract Classes and Methods

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 ABC Class in the abc Module

Class

Explanation

ABC

Abstract base class for convenience in defining an abstract class. The abstract class specifies ABC as its superclass.

TABLE B.20 The abstractmethod Decorator in the abc Module

Decorator

Explanation

@abstractmethod

Decorator that converts a method to an abstract method.

B.11.8 Multithreading

The threading module provides support for defining a multithreaded application. A multithreaded application needs to perform these three actions:

  1. The class should inherit from the Thread class. Ex: class MyApp(Thread)

  2. The class should define a run method that contains the code for the thread to execute.

  3. 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 run and start Methods in the Thread Class

Method

Description

run()

The method that contains the code to do the work of the thread. The subclass provides its own version of this method.

start()

Creates the thread and calls the thread’s run method. This method can be called only once per thread.

B.12 Regular Expression Patterns

The following is a list of some simple regular expression patterns:

.

Match any single character.

[abc]

Match a, b, or c.

[^abc]

Match any characters other than a, b, or c.

[abc]+

Match one or more occurrences of the characters abc—for example, match b or aba or ccba.

[abc]+[de]*

Match zero or more occurrences of the characters abcde—for example, match b or aba or bd or abae.

(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

match(pattern, string)

re.match('[abc]XY.', ‘aXYv’)

Matches any string that starts with a, b, or c, followed by XY, followed by any single character. Returns a match object on success or None.

sub(pattern, replacement, string)

re.sub('[tv]', 'X','vxyzbgtt')

Returns 'XxyzbgXX'. Similar to replace, except that regular expression matching is used.

findall(pattern, string)

{re.findall('[bc]+', 'abcdefedcba')

Returns ['bc','cb']. Returns a list of all substrings matching the regular expression.

groups()

matchObj.groups()

Returns a list of all capture groups matched. matchObj is created by a call to match.

group(i)

matchObj.group(2)

Returns a single capture group at index 2. matchObj is created by a call to match.

B.13 Defining Functions

Image

B.14 Defining Classes

Image

B.15 Deleting Objects

The del statement is used to delete objects, such as variables, functions, and items in mutable sequences.

Deleting a function:

Image

Deleting an object:

Image

Deleting a list item:

Image

Deleting a dictionary item:

Image

B.16 Common Error Messages

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.

Image

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.

Image

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).

Image

LISTING B.1 A simple Python traceback

When we run this program we get the following output:

Image

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:

Image

Here is another situation where Python cannot figure out what to add:

Image

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:

Image

The next error is fairly easy to recognize, but it happens commonly:

Image

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.

Image
..................Content has been hidden....................

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