Free Essay

Advantages of Phase Modulation

In:

Submitted By salmak
Words 14272
Pages 58
Python Reference Manual
Release 2.3.3

Guido van Rossum Fred L. Drake, Jr., editor

December 19, 2003

PythonLabs Email: docs@python.org Copyright c 2001, 2002, 2003 Python Software Foundation. All rights reserved. Copyright c 2000 BeOpen.com. All rights reserved. Copyright c 1995-2000 Corporation for National Research Initiatives. All rights reserved. Copyright c 1991-1995 Stichting Mathematisch Centrum. All rights reserved. See the end of this document for complete license and permissions information.

Abstract Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for rapid application development, as well as for use as a scripting or glue language to connect existing components together. Python’s simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed. This reference manual describes the syntax and “core semantics” of the language. It is terse, but attempts to be exact and complete. The semantics of non-essential built-in object types and of the built-in functions and modules are described in the Python Library Reference. For an informal introduction to the language, see the Python Tutorial. For C or C++ programmers, two additional manuals exist: Extending and Embedding the Python Interpreter describes the high-level picture of how to write a Python extension module, and the Python/C API Reference Manual describes the interfaces available to C/C++ programmers in detail.

CONTENTS

1 2

Introduction 1.1 Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Lexical analysis 2.1 Line structure . . . . . . 2.2 Other tokens . . . . . . 2.3 Identifiers and keywords 2.4 Literals . . . . . . . . . 2.5 Operators . . . . . . . . 2.6 Delimiters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1 1 3 3 6 6 7 10 10 13 13 14 20 33 33 34 37 37 37 39 42 43 43 44 44 44 46 46 46 47 47 49 49 49 50 i

3

Data model 3.1 Objects, values and types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 The standard type hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.3 Special method names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Execution model 4.1 Naming and binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Expressions 5.1 Arithmetic conversions . . . 5.2 Atoms . . . . . . . . . . . 5.3 Primaries . . . . . . . . . . 5.4 The power operator . . . . . 5.5 Unary arithmetic operations 5.6 Binary arithmetic operations 5.7 Shifting operations . . . . . 5.8 Binary bit-wise operations . 5.9 Comparisons . . . . . . . . 5.10 Boolean operations . . . . . 5.11 Lambdas . . . . . . . . . . 5.12 Expression lists . . . . . . . 5.13 Evaluation order . . . . . . 5.14 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4

5

6

Simple statements 6.1 Expression statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Assert statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 Assignment statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 7

The pass statement . . . The del statement . . . The print statement . . The return statement . The yield statement . . The raise statement . . The break statement . . The continue statement The import statement . The global statement . The exec statement . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . .

52 52 53 53 53 54 54 55 55 57 57 59 60 60 60 61 62 63 65 65 65 65 66 67 67 68 71

Compound statements 7.1 The if statement . . . 7.2 The while statement 7.3 The for statement . . 7.4 The try statement . . 7.5 Function definitions . 7.6 Class definitions . . .

8

Top-level components 8.1 Complete Python programs 8.2 File input . . . . . . . . . . 8.3 Interactive input . . . . . . 8.4 Expression input . . . . . .

A History and License A.1 History of the software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.2 Terms and conditions for accessing or otherwise using Python . . . . . . . . . . . . . . . . . . . . . Index

ii

CHAPTER

ONE

Introduction
This reference manual describes the Python programming language. It is not intended as a tutorial. While I am trying to be as precise as possible, I chose to use English rather than formal specifications for everything except syntax and lexical analysis. This should make the document more understandable to the average reader, but will leave room for ambiguities. Consequently, if you were coming from Mars and tried to re-implement Python from this document alone, you might have to guess things and in fact you would probably end up implementing quite a different language. On the other hand, if you are using Python and wonder what the precise rules about a particular area of the language are, you should definitely be able to find them here. If you would like to see a more formal definition of the language, maybe you could volunteer your time — or invent a cloning machine :-). It is dangerous to add too many implementation details to a language reference document — the implementation may change, and other implementations of the same language may work differently. On the other hand, there is currently only one Python implementation in widespread use (although a second one now exists!), and its particular quirks are sometimes worth being mentioned, especially where the implementation imposes additional limitations. Therefore, you’ll find short “implementation notes” sprinkled throughout the text. Every Python implementation comes with a number of built-in and standard modules. These are not documented here, but in the separate Python Library Reference document. A few built-in modules are mentioned when they interact in a significant way with the language definition.

1.1 Notation
The descriptions of lexical analysis and syntax use a modified BNF grammar notation. This uses the following style of definition: name: lc_letter: lc_letter (lc_letter | "_")* "a"..."z"

The first line says that a name is an lc letter followed by a sequence of zero or more lc letters and underscores. An lc letter in turn is any of the single characters ‘a’ through ‘z’. (This rule is actually adhered to for the names defined in lexical and grammar rules in this document.) Each rule begins with a name (which is the name defined by the rule) and a colon. A vertical bar (|) is used to separate alternatives; it is the least binding operator in this notation. A star (*) means zero or more repetitions of the preceding item; likewise, a plus (+) means one or more repetitions, and a phrase enclosed in square brackets ([ ]) means zero or one occurrences (in other words, the enclosed phrase is optional). The * and + operators bind as tightly as possible; parentheses are used for grouping. Literal strings are enclosed in quotes. White space is only meaningful to separate tokens. Rules are normally contained on a single line; rules with many alternatives may be formatted alternatively with each line after the first beginning with a vertical bar.

1

In lexical definitions (as the example above), two more conventions are used: Two literal characters separated by three dots mean a choice of any single character in the given (inclusive) range of ASCII characters. A phrase between angular brackets () gives an informal description of the symbol defined; e.g., this could be used to describe the notion of ‘control character’ if needed. Even though the notation used is almost the same, there is a big difference between the meaning of lexical and syntactic definitions: a lexical definition operates on the individual characters of the input source, while a syntax definition operates on the stream of tokens generated by the lexical analysis. All uses of BNF in the next chapter (“Lexical Analysis”) are lexical definitions; uses in subsequent chapters are syntactic definitions.

2

Chapter 1. Introduction

CHAPTER

TWO

Lexical analysis
A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer. This chapter describes how the lexical analyzer breaks a file into tokens. Python uses the 7-bit ASCII character set for program text. New in version 2.3: An encoding declaration can be used to indicate that string literals and comments use an encoding different from ASCII.. For compatibility with older versions, Python only warns if it finds 8-bit characters; those warnings should be corrected by either declaring an explicit encoding, or using escape sequences if those bytes are binary data, instead of characters. The run-time character set depends on the I/O devices connected to the program but is generally a superset of ASCII. Future compatibility note: It may be tempting to assume that the character set for 8-bit characters is ISO Latin-1 (an ASCII superset that covers most western languages that use the Latin alphabet), but it is possible that in the future Unicode text editors will become common. These generally use the UTF-8 encoding, which is also an ASCII superset, but with very different use for the characters with ordinals 128-255. While there is no consensus on this subject yet, it is unwise to assume either Latin-1 or UTF-8, even though the current implementation appears to favor Latin-1. This applies both to the source character set and the run-time character set.

2.1

Line structure

A Python program is divided into a number of logical lines.

2.1.1 Logical lines
The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.

2.1.2 Physical lines
A physical line ends in whatever the current platform’s convention is for terminating lines. On U NIX, this is the ASCII LF (linefeed) character. On Windows, it is the ASCII sequence CR LF (return followed by linefeed). On Macintosh, it is the ASCII CR (return) character.

2.1.3 Comments
A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax; they are not tokens. 3

2.1.4 Encoding declarations
If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([\w- .]+) , this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file. The recommended forms of this expression are
# -*- coding: -*-

which is recognized also by GNU Emacs, and
# vim:fileencoding=

which is recognized by Bram Moolenar’s VIM. In addition, if the first bytes of the file are the UTF-8 byte-order mark (’\xef\xbb\xbf’), the declared file encoding is UTF-8 (this is supported, among others, by Microsoft’s notepad). If an encoding is declared, the encoding name must be recognized by Python. The encoding is used for all lexical analysis, in particular to find the end of a string, and to interpret the contents of Unicode literals. String literals are converted to Unicode for syntactical analysis, then converted back to their original encoding before interpretation starts. The encoding declaration must appear on a line of its own.

2.1.5 Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example: if 1900 < year < 2100 and 1 > def f(a, b): ... print a, b ... >>> f(b=1, *(2,)) 2 1 >>> f(a=1, *(2,)) Traceback (most recent call last): File "", line 1, in ? TypeError: f() got multiple values for keyword argument ’a’ >>> f(1, *(2,)) 1 2

It is unusual for both keyword arguments and the ‘*expression’ syntax to be used in the same call, so in practice this confusion does not arise. If the syntax ‘**expression’ appears in the function call, ‘expression’ must evaluate to a (subclass of) dictionary, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both ‘expression’ and as an explicit keyword argument, a TypeError exception is raised. Formal parameters using the syntax ‘*identifier’ or ‘**identifier’ cannot be used as positional argument slots or as keyword argument names. Formal parameters using the syntax ‘(sublist)’ cannot be used as keyword argument names; the outermost sublist corresponds to a single unnamed argument slot, and the argument value is assigned to the sublist using the usual tuple assignment rules after all other parameter processing is done. A call always returns some value, possibly None, unless it raises an exception. How this value is computed depends on the type of the callable object. If it is— a user-defined function: The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section 7.5. When the code block executes a return statement, this specifies the return value of the function call. a built-in function or method: The result is up to the interpreter; see the Python Library Reference for the descriptions of built-in functions and methods. a class object: A new instance of that class is returned. a class instance method: The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument. a class instance: The class must define a called. call () method; the effect is then the same as if that method was

5.4 The power operator
The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is: power ::= primary ["**" u expr]

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands). The power operator has the same semantics as the built-in pow() function, when called with two arguments: it yields its left argument raised to the power of its right argument. The numeric arguments are first converted to a common type. The result type is that of the arguments after coercion. 42 Chapter 5. Expressions

With mixed operand types, the coercion rules for binary arithmetic operators apply. For int and long int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. (This last feature was added in Python 2.2. In Python 2.1 and before, if both arguments were of integer types and the second argument was negative, an exception was raised). Raising 0.0 to a negative power results in a ZeroDivisionError. Raising a negative number to a fractional power results in a ValueError.

5.5

Unary arithmetic operations
::=

All unary arithmetic (and bit-wise) operations have the same priority: u expr power | "-" u expr | "+" u expr | "˜" u expr

The unary - (minus) operator yields the negation of its numeric argument. The unary + (plus) operator yields its numeric argument unchanged. The unary ˜ (invert) operator yields the bit-wise inversion of its plain or long integer argument. The bit-wise inversion of x is defined as -(x+1). It only applies to integral numbers. In all three cases, if the argument does not have the proper type, a TypeError exception is raised.

5.6

Binary arithmetic operations

The binary arithmetic operations have the conventional priority levels. Note that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators: m expr a expr ::= ::= u expr | m expr "*" u expr | m expr "//" u expr | m expr "/" u expr | m expr "%" u expr m expr | a expr "+" m expr | a expr "-" m expr

The * (multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer (plain or long) and the other must be a sequence. In the former case, the numbers are converted to a common type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence. The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the ZeroDivisionError exception. The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand1 . The integer division and modulo operators are connected by the following identity: x == (x/y)*y + (x%y). Integer division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x/y,
1 While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff. For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 %1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100. Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.

5.5. Unary arithmetic operations

43

x%y). These identities don’t hold for floating point numbers; there similar identities hold approximately where x/y is replaced by floor(x/y) or floor(x/y) - 12 . Deprecated since release 2.3. The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate. The + (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated. The - (subtraction) operator yields the difference of its arguments. The numeric arguments are first converted to a common type.

5.7 Shifting operations
The shifting operations have lower priority than the arithmetic operations: shift expr ::= a expr | shift expr ( "" ) a expr

These operators accept plain or long integers as arguments. The arguments are converted to a common type. They shift the first argument to the left or right by the number of bits given by the second argument. A right shift by n bits is defined as division by pow(2,n). A left shift by n bits is defined as multiplication with pow(2,n); for plain integers there is no overflow check so in that case the operation drops bits and flips the sign if the result is not less than pow(2,31) in absolute value. Negative shift counts raise a ValueError exception.

5.8

Binary bit-wise operations
::= ::= ::=

Each of the three bitwise operations has a different priority level: and expr xor expr or expr shift expr | and expr "&" shift expr and expr | xor expr "ˆ" and expr xor expr | or expr "|" xor expr

The & operator yields the bitwise AND of its arguments, which must be plain or long integers. The arguments are converted to a common type. The ˆ operator yields the bitwise XOR (exclusive OR) of its arguments, which must be plain or long integers. The arguments are converted to a common type. The | operator yields the bitwise (inclusive) OR of its arguments, which must be plain or long integers. The arguments are converted to a common type.

5.9 Comparisons
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics: comparison comp operator ::= ::= or expr ( comp operator or expr )* "" | "==" | ">=" | ">=" | "" expression [("," expression)+ [","]] )

print stmt

print evaluates each expression in turn and writes the resulting object to standard output (see below). If an object is not a string, it is first converted to a string using the rules for string conversions. The (resulting or original) string is then written. A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is ‘\n’, or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.) Note: Objects which act like file objects but which are not the built-in file objects often do not properly emulate this aspect of the file object’s behavior, so it is best not to rely on this. A ‘\n’ character is written at the end, unless the print statement ends with a comma. This is the only action if the statement contains just the keyword print. Standard output is defined as the file object named stdout in the built-in module sys. If no such object exists, or if it does not have a write() method, a RuntimeError exception is raised. print also has an extended form, defined by the second portion of the syntax described above. This form is sometimes referred to as “print chevron.” In this form, the first expression after the >> must evaluate to a “file-like” object, specifically an object that has a write() method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates to None, then sys.stdout is used as the file for output.

6.7 The return statement return stmt ::= "return" [expression list] return may only occur syntactically nested in a function definition, not within a nested class definition. If an expression list is present, it is evaluated, else None is substituted. return leaves the current function call with the expression list (or None) as return value. When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function. In a generator function, the return statement is not allowed to include an expression list. In that context, a bare return indicates that the generator is done and will cause StopIteration to be raised.

6.8

The yield statement
::= "yield" expression list

yield stmt

The yield statement is only used when defining a generator function, and is only used in the body of the generator function. Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. When a generator function is called, it returns an iterator known as a generator iterator, or more commonly, a generator. 6.6. The print statement 53

The body of the generator function is executed by calling the generator’s next() method repeatedly until it raises an exception. When a yield statement is executed, the state of the generator is frozen and the value of expression list is returned to next()’s caller. By “frozen” we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time next() is invoked, the function can proceed exactly as if the yield statement were just another external call. The yield statement is not allowed in the try clause of a try ... finally construct. The difficulty is that there’s no guarantee the generator will ever be resumed, hence no guarantee that the finally block will ever get executed. Note: In Python 2.2, the yield statement is only allowed when the generators feature has been enabled. It will always be enabled in Python 2.3. This future import statment can be used to enable the feature: from __future__ import generators

See Also: PEP 0255, “Simple Generators” The proposal for adding generators and the yield statement to Python.

6.9 The raise statement raise stmt ::= "raise" [expression ["," expression ["," expression]]] If no expressions are present, raise re-raises the last expression that was active in the current scope. If no exception is active in the current scope, an exception is raised indicating this error. Otherwise, raise evaluates the expressions to get three objects, using None as the value of omitted expressions. The first two objects are used to determine the type and value of the exception. If the first object is an instance, the type of the exception is the class of the instance, the instance itself is the value, and the second object must be None. If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value. If a third object is present and not None, it must be a traceback object (see section 3.2), and it is substituted instead of the current location as the place where the exception occurred. If the third object is present and not a traceback object or None, a TypeError exception is raised. The three-expression form of raise is useful to re-raise an exception transparently in an except clause, but raise with no expressions should be preferred if the exception to be re-raised was the most recently active exception in the current scope. Additional information on exceptions can be found in section 4.2, and information about handling exceptions is in section 7.4.

6.10

The break statement
::= "break"

break stmt

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. 54 Chapter 6. Simple statements

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one. If a for loop is terminated by break, the loop control target keeps its current value. When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

6.11

The continue statement
::= "continue"

continue stmt

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or try statement within that loop.1 It continues with the next cycle of the nearest enclosing loop.

6.12 The import statement import stmt ::= "import" module ["as" name] ( "," module ["as" name] )* | "from" module "import" identifier ["as" name] ( "," identifier ["as" name] )* | "from" module "import" "*" (identifier ".")* identifier

module

::=

Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly. In this context, to “initialize” a built-in or extension module means to call an initialization function that the module must provide for the purpose (in the reference implementation, the function’s name is obtained by prepending string “init” to the module’s name); to “initialize” a Python-coded module means to execute the module’s body. The system maintains a table of modules that have been or are being initialized, indexed by module name. This table is accessible as sys.modules. When a module name is found in this table, step (1) is finished. If not, a search for a module definition is started. When a module is found, it is loaded. Details of the module searching and loading process are implementation and platform specific. It generally involves searching for a “built-in” module with the given name and then searching a list of locations given as sys.path. If a built-in module is found, its built-in initialization code is executed and step (1) is finished. If no matching file is found, ImportError is raised. If a file is found, it is parsed, yielding an executable code block. If a syntax error occurs, SyntaxError is raised. Otherwise, an empty module of the given name is created and inserted in the module table, and then the code block is executed in the context of this module. Exceptions during this execution terminate step (1). When step (1) finishes without raising an exception, step (2) can begin. The first form of import statement binds the module name in the local namespace to the module object, and then goes on to import the next identifier, if any. If the module name is followed by as, the name following as is used as the local name for the module. The from form does not bind the module name: it goes through the list of identifiers, looks each one of them up in the module found in step (1), and binds the name in the local namespace to the object thus found. As with the first form of import, an alternate local name can be supplied by specifying ”as localname”. If a name is not found, ImportError is raised. If the list of identifiers is replaced by a star (‘*’), all public names defined in the module are bound in the local namespace of the import statement..
1 It may occur within an except or else clause. The restriction on occurring in the try clause is implementor’s laziness and will eventually be lifted.

6.11. The continue statement

55

The public names defined by a module are determined by checking the module’s namespace for a variable named all ; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in all are all considered public and are required to exist. If all is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character (‘ ’). all should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module). The from form with ‘*’ may only occur in a module scope. If the wild card form of import — ‘import *’ — is used in a function and the function contains or is a nested block with free variables, the compiler will raise a SyntaxError. Hierarchical module names: when the module names contains one or more dots, the module search path is carried out differently. The sequence of identifiers up to the last dot is used to find a “package”; the final identifier is then searched inside the package. A package is generally a subdirectory of a directory on sys.path that has a file ‘ init .py’. [XXX Can’t be bothered to spell this out right now; see the URL http://www.python.org/doc/essays/packages.html for more details, also about how the module search works from inside a package.] The built-in function import () is provided to support applications that determine which modules need to be loaded dynamically; refer to Built-in Functions in the Python Library Reference for additional information.

6.12.1 Future statements
A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard. future statement feature name ::= ::= ::= "from" " future " "import" feature ["as" name] ("," feature ["as" name])* identifier identifier

A future statement must appear near the top of the module. The only lines that can appear before a future statement are: • the module docstring (if any), • comments, • blank lines, and • other future statements. The features recognized by Python 2.3 are ‘generators’, ‘division’ and ‘nested scopes’. ‘generators’ and ‘nested scopes’ are redundant in 2.3 because they are always enabled. A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime. For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it. The direct runtime semantics are the same as for any import statement: there is a standard module described later, and it will be imported in the usual way at the time the future statement is executed. The interesting runtime semantics depend on the specific feature enabled by the future statement. future ,

56

Chapter 6. Simple statements

Note that there is nothing special about the statement: import __future__ [as name]

That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions. Code compiled by an exec statement or calls to the builtin functions compile() and execfile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can, starting with Python 2.2 be controlled by optional arguments to compile() — see the documentation of that function in the library reference for details. A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.

6.13

The global statement
::= "global" identifier ("," identifier)*

global stmt

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global. Names listed in a global statement must not be used in the same code block textually preceding that global statement. Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement. (The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.) Programmer’s note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in an exec statement does not affect the code block containing the exec statement, and code contained in an exec statement is unaffected by global statements in the code containing the exec statement. The same applies to the eval(), execfile() and compile() functions.

6.14

The exec statement
::= "exec" expression ["in" expression ["," expression]]

exec stmt

This statement supports dynamic execution of Python code. The first expression should evaluate to either a string, an open file object, or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). If it is an open file, the file is parsed until EOF and executed. If it is a code object, it is simply executed. In all cases, if the optional parts are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, both must be dictionaries and they are used for the global and local variables, respectively. As a side effect, an implementation may insert additional keys into the dictionaries given besides those corresponding to variable names set by the executed code. For example, the current implementation may add a reference to the dictionary of the built-in module builtin under the key builtins (!). Programmer’s hints: dynamic evaluation of expressions is supported by the built-in function eval(). The built-in

6.13. The global statement

57

functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use by exec.

58

Chapter 6. Simple statements

CHAPTER

SEVEN

Compound statements
Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line. The if, while and for statements implement traditional control flow constructs. try specifies exception handlers and/or cleanup code for a group of statements. Function and class definitions are also syntactically compound statements. Compound statements consist of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong: if test1: if test2: print x

Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print statements are executed: if x < y < z: print x; print y; print z

Summarizing: compound stmt ::= if stmt | while stmt | for stmt | try stmt | funcdef | classdef stmt list NEWLINE | NEWLINE INDENT statement+ DEDENT stmt list NEWLINE | compound stmt simple stmt (";" simple stmt)* [";"]

suite statement stmt list

::= ::= ::=

Note that statements always end in a NEWLINE possibly followed by a DEDENT. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the ‘dangling else’ problem is solved in Python by requiring nested if statements to be indented). The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.

59

7.1

The if statement if stmt ::= "if" expression ":" suite ( "elif" expression ":" suite )* ["else" ":" suite]

The if statement is used for conditional execution:

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section 5.10 for the definition of true and false); then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause, if present, is executed.

7.2 The while statement
The while statement is used for repeated execution as long as an expression is true: while stmt ::= "while" expression ":" suite ["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates. A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

7.3

The for statement

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object: for stmt ::= "for" target list "in" expression list ":" suite ["else" ":" suite]

The expression list is evaluated once; it should yield a sequence. The suite is then executed once for each item in the sequence, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates. A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item. The suite may assign to the variable(s) in the target list; this does not affect the next item assigned to it. The target list is not deleted when the loop is finished, but if the sequence is empty, it will not have been assigned to at all by the loop. Hint: the built-in function range() returns a sequence of integers suitable to emulate the effect of Pascal’s for i := a to b do; e.g., range(3) returns the list [0, 1, 2]. Warning: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

60

Chapter 7. Compound statements

for x in a[:]: if x < 0: a.remove(x)

7.4

The try statement
::= ::=

The try statement specifies exception handlers and/or cleanup code for a group of statements: try stmt try exc stmt try exc stmt | try fin stmt "try" ":" suite ("except" [expression ["," target]] ":" suite)+ ["else" ":" suite] "try" ":" suite "finally" ":" suite

try fin stmt

::=

There are two forms of try statement: try...except and try...finally. These forms cannot be mixed (but they can be nested in each other). The try...except form specifies one or more exception handlers (the except clauses). When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception, or it is a tuple containing an item that is compatible with the exception. Note that the object identities must match, i.e. it must be the same object, not just an object with the same value. If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire try statement raised the exception). When a matching except clause is found, the exception’s parameter is assigned to the target specified in that except clause, if present, and the except clause’s suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.) Before an except clause’s suite is executed, details about the exception are assigned to three variables in the sys module: sys.exc type receives the object identifying the exception; sys.exc value receives the exception’s parameter; sys.exc traceback receives a traceback object (see section 3.2) identifying the point in the program where the exception occurred. These details are also available through the sys.exc info() function, which returns a tuple (exc type, exc value, exc traceback). Use of the corresponding variables is deprecated in favor of this function, since their use is unsafe in a threaded program. As of Python 1.5, the variables are restored to their previous values (before the call) when returning from a function that handled an exception. The optional else clause is executed if and when control flows off the end of the try clause.1 Exceptions in the else clause are not handled by the preceding except clauses. The try...finally form specifies a ‘cleanup’ handler. The try clause is executed. When no exception occurs, the finally clause is executed. When an exception occurs in the try clause, the exception is temporarily saved, the finally clause is executed, and then the saved exception is re-raised. If the finally clause raises another exception or executes a return or break statement, the saved exception is lost. A continue statement is illegal
1 Currently,

control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

7.4. The try statement

61

in the finally clause. (The reason is a problem with the current implementation – this restriction may be lifted in the future). The exception information is not available to the program during execution of the finally clause. When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future). Additional information on exceptions can be found in section 4.2, and information on using the raise statement to generate exceptions may be found in section 6.9.

7.5

Function definitions
::= ::=

A function definition defines a user-defined function object (see section 3.2): funcdef parameter list "def" funcname "(" [parameter list] ")" ":" suite (defparameter ",")* ("*" identifier [, "**" identifier] | "**" identifier | defparameter [","]) parameter ["=" expression] parameter ("," parameter)* [","] identifier | "(" sublist ")" identifier

defparameter sublist parameter funcname

::= ::= ::= ::=

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called. The function definition does not execute the function body; this gets executed only when the function is called. When one or more top-level parameters have the form parameter = expression, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters must also have a default value — this is a syntactic restriction that is not expressed by the grammar. Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.: def whats_on_the_telly(penguin=None): if penguin is None: penguin = [] penguin.append("property of the zoo") return penguin

Function call semantics are described in more detail in section 5.3.4. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary. It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda forms, described in section 5.11. Note that the lambda form is merely a shorthand for a simplified function definition; a function defined in a “def” statement can be passed around or assigned to another name just 62 Chapter 7. Compound statements

like a function defined by a lambda form. The “def” form is actually more powerful since it allows the execution of multiple statements. Programmer’s note: Functions are first-class objects. A “def” form executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section 4.1 for details.

7.6

Class definitions
::= ::= ::=

A class definition defines a class object (see section 3.2): classdef inheritance classname "class" classname [inheritance] ":" suite "(" [expression list] ")" identifier

A class definition is an executable statement. It first evaluates the inheritance list, if present. Each item in the inheritance list should evaluate to a class object. The class’s suite is then executed in a new execution frame (see section 4.1), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace. Programmer’s note: variables defined in the class definition are class variables; they are shared by all instances. To define instance variables, they must be given a value in the init () method or in another method. Both class and instance variables are accessible through the notation “self.name”, and an instance variable hides a class variable with the same name when accessed in this way. Class variables with immutable values can be used as defaults for instance variables.

7.6. Class definitions

63

64

CHAPTER

EIGHT

Top-level components
The Python interpreter can get its input from a number of sources: from a script passed to it as standard input or as program argument, typed in interactively, from a module source file, etc. This chapter gives the syntax used in these cases.

8.1 Complete Python programs
While a language specification need not prescribe how the language interpreter is invoked, it is useful to have a notion of a complete Python program. A complete Python program is executed in a minimally initialized environment: all built-in and standard modules are available, but none have been initialized, except for sys (various system services), builtin (built-in functions, exceptions and None) and main . The latter is used to provide the local and global namespace for execution of the complete program. The syntax for a complete Python program is that for file input, described in the next section. The interpreter may also be invoked in interactive mode; in this case, it does not read and execute a complete program but reads and executes one statement (possibly compound) at a time. The initial environment is identical to that of a complete program; each statement is executed in the namespace of main . Under U NIX, a complete program can be passed to the interpreter in three forms: with the -c string command line option, as a file passed as the first command line argument, or as standard input. If the file or standard input is a tty device, the interpreter enters interactive mode; otherwise, it executes the file as a complete program.

8.2

File input
::=

All input read from non-interactive files has the same form: file input (NEWLINE | statement)*

This syntax is used in the following situations: • when parsing a complete Python program (from a file or from a string); • when parsing a module; • when parsing a string passed to the exec statement;

8.3 Interactive input
Input in interactive mode is parsed using the following grammar: 65

interactive input

::=

[stmt list] NEWLINE | compound stmt NEWLINE

Note that a (top-level) compound statement must be followed by a blank line in interactive mode; this is needed to help the parser detect the end of the input.

8.4

Expression input

There are two forms of expression input. Both ignore leading whitespace. The string argument to eval() must have the following form: eval input ::= expression list NEWLINE*

The input line read by input() must have the following form: input input ::= expression list NEWLINE

Note: to read ‘raw’ input line without interpretation, you can use the built-in function raw input() or the readline() method of file objects.

66

Chapter 8. Top-level components

APPENDIX

A

History and License
A.1 History of the software
Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands as a successor of a language called ABC. Guido remains Python’s principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us/) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation; see http://www.zope.com/). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org/ for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. Release 0.9.0 thru 1.2 1.3 thru 1.5.2 1.6 2.0 1.6.1 2.1 2.0.1 2.1.1 2.2 2.1.2 2.1.3 2.2.1 2.2.2 2.2.3 2.3 2.3.1 2.3.2 Derived from n/a 1.2 1.5.2 1.6 1.6 2.0+1.6.1 2.0+1.6.1 2.1+2.0.1 2.1.1 2.1.1 2.1.2 2.2 2.2.1 2.2.2 2.2.2 2.3 2.3.1 Year 1991-1995 1995-1999 2000 2000 2001 2001 2001 2001 2001 2002 2002 2002 2002 2002-2003 2002-2003 2002-2003 2003 Owner CWI CNRI CNRI BeOpen.com CNRI PSF PSF PSF PSF PSF PSF PSF PSF PSF PSF PSF PSF GPL compatible? yes yes no no no no yes yes yes yes yes yes yes yes yes yes yes

Note: GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don’t. Thanks to the many outside volunteers who have worked under Guido’s direction to make these releases possible. 67

A.2 Terms and conditions for accessing or otherwise using Python
PSF LICENSE AGREEMENT FOR PYTHON 2.3.3 1. This LICENSE AGREEMENT is between the Python Software Foundation (“PSF”), and the Individual or Organization (“Licensee”) accessing and otherwise using Python 2.3.3 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 2.3.3 alone or in any derivative version, provided, however, that PSF’s License Agreement and PSF’s notice of copyright, i.e., “Copyright c 2001-2003 Python Software Foundation; All Rights Reserved” are retained in Python 2.3.3 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 2.3.3 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 2.3.3. 4. PSF is making Python 2.3.3 available to Licensee on an “AS IS” basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.3.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python 2.3.3, Licensee agrees to be bound by the terms and conditions of this License Agreement. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 1. This LICENSE AGREEMENT is between BeOpen.com (“BeOpen”), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization (“Licensee”) accessing and otherwise using this software in source or binary form and its associated documentation (“the Software”). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an “AS IS” basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

68

Appendix A. History and License

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the “BeOpen Python” logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 (“CNRI”), and the Individual or Organization (“Licensee”) accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI’s License Agreement and CNRI’s notice of copyright, i.e., “Copyright c 1995-2001 Corporation for National Research Initiatives; All Rights Reserved” are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI’s License Agreement, Licensee may substitute the following text (omitting the quotes): “Python 1.6.1 is made available subject to the terms and conditions in CNRI’s License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013.” 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an “AS IS” basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia’s conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, A.2. Terms and conditions for accessing or otherwise using Python 69

and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the “ACCEPT” button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ACCEPT CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 Copyright c 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

70

Appendix A. History and License

INDEX

Symbols abs () (numeric object method), 29 add () (numeric object method), 28 add () (sequence object method), 26 all (optional module attribute), 56 and () (numeric object method), 28 bases (class attribute), 18 builtin (built-in module), 57, 65 builtins , 57 call () (object method), 26 call () (object method), 42 class (instance attribute), 19 cmp () (object method), 22 cmp () (object method), 22 coerce () (numeric object method), 30 coerce () (numeric object method), 26 complex () (numeric object method), 29 contains () (container object method), 27 contains () (mapping object method), 26 contains () (sequence object method), 26 debug , 50 del () (object method), 21 delattr () (object method), 23 delete () (object method), 24 delitem () (container object method), 26 delslice () (sequence object method), 27 dict (class attribute), 18 dict (function attribute), 16 dict (instance attribute), 19, 23 dict (module attribute), 18 div () (numeric object method), 29 divmod () (numeric object method), 28 doc (class attribute), 18 doc (function attribute), 16 doc (method attribute), 16 doc (module attribute), 18 eq () (object method), 22 file (module attribute), 18 float () (numeric object method), 29 floordiv () (numeric object method), 28 ge () (object method), 22

get () (object method), 23 getattr () (object method), 23 getattribute () (object method), 23 getitem () (container object method), 26 getitem () (mapping object method), 20 getslice () (sequence object method), 27 gt () (object method), 22 hash () (object method), 22 hex () (numeric object method), 30 iadd () (numeric object method), 29 iadd () (sequence object method), 26 iand () (numeric object method), 29 idiv () (numeric object method), 29 ifloordiv () (numeric object method), 29 ilshift () (numeric object method), 29 imod () (numeric object method), 29 import () (built-in function), 56 imul () (numeric object method), 29 imul () (sequence object method), 26 init () (object method), 21 init () (object method), 18 init .py, 56 int () (numeric object method), 29 invert () (numeric object method), 29 ior () (numeric object method), 29 ipow () (numeric object method), 29 irshift () (numeric object method), 29 isub () (numeric object method), 29 iter () (container object method), 26 iter () (sequence object method), 26 itruediv () (numeric object method), 29 ixor () (numeric object method), 29 le () (object method), 22 len () (container object method), 26 len () (mapping object method), 22 long () (numeric object method), 29 lshift () (numeric object method), 28 lt () (object method), 22 main (built-in module), 34, 65 metaclass (data in ), 25 mod () (numeric object method), 28 module (class attribute), 18 71

module (function attribute), 16 module (method attribute), 16 mul () (numeric object method), 28 mul () (sequence object method), 26 name (class attribute), 18 name (function attribute), 16 name (method attribute), 16 name (module attribute), 18 ne () (object method), 22 neg () (numeric object method), 29 nonzero () (object method), 22 nonzero () (object method), 26 oct () (numeric object method), 30 or () (numeric object method), 28 pos () (numeric object method), 29 pow () (numeric object method), 28 radd () (numeric object method), 29 radd () (sequence object method), 26 rand () (numeric object method), 29 rcmp () (object method), 22 rdiv () (numeric object method), 29 rdivmod () (numeric object method), 29 repr () (object method), 21 rfloordiv () (numeric object method), 29 rlshift () (numeric object method), 29 rmod () (numeric object method), 29 rmul () (numeric object method), 29 rmul () (sequence object method), 26 ror () (numeric object method), 29 rpow () (numeric object method), 29 rrshift () (numeric object method), 29 rshift () (numeric object method), 28 rsub () (numeric object method), 29 rtruediv () (numeric object method), 29 rxor () (numeric object method), 29 set () (object method), 23 setattr () (object method), 23 setattr () (object method), 23 setitem () (container object method), 26 setslice () (sequence object method), 27 slots (data in ), 24 str () (object method), 21 sub () (numeric object method), 28 truediv () (numeric object method), 29 unicode () (object method), 22 xor () (numeric object method), 28

anonymous function, 46 append() (sequence object method), 26 argument function, 16 arithmetic conversion, 37 operation, binary, 43 operation, unary, 43 array (standard module), 16 ASCII , 2, 7, 8, 11, 15 assert statement, 49 AssertionError exception, 50 assertions debugging, 49 assignment attribute, 50, 51 augmented, 51 class attribute, 18 class instance attribute, 19 slicing, 51 statement, 16, 50 subscription, 51 target list, 50 atom, 37 attribute, 14 assignment, 50, 51 assignment, class, 18 assignment, class instance, 19 class, 18 class instance, 18 deletion, 53 generic special, 14 reference, 39 special, 14 AttributeError exception, 40 augmented assignment, 51

B back-quotes, 21, 39 backslash character, 4 backward quotes, 21, 39 binary arithmetic operation, 43 bit-wise operation, 44 binding global name, 57 name, 33, 50, 55, 62, 63 bit-wise Index

A abs() (built-in function), 29 addition, 44 and bit-wise, 44 and operator, 46 72

and, 44 operation, binary, 44 operation, unary, 43 or, 44 xor, 44 blank line, 5 block, 33 code, 33 BNF, 1, 37 Boolean object, 14 operation, 46 break statement, 54, 60–62 bsddb (standard module), 16 built-in method, 17 module, 55 built-in function call, 42 object, 17, 42 built-in method call, 42 object, 17, 42 byte, 15 bytecode, 19

C
C, 8 language, 14, 15, 17, 44 call, 41 built-in function, 42 built-in method, 42 class instance, 42 class object, 18, 42 function, 16, 42 instance, 26, 42 method, 42 procedure, 49 user-defined function, 42 callable object, 16, 41 chaining comparisons, 45 character, 15, 40 character set, 15 chr() (built-in function), 15 class attribute, 18 attribute assignment, 18 constructor, 21 definition, 53, 63 instance, 18 name, 63 Index

object, 18, 42, 63 class statement, 63 class instance attribute, 18 attribute assignment, 19 call, 42 object, 18, 42 class object call, 18, 42 clause, 59 clear() (mapping object method), 26 cmp() (built-in function), 22 co argcount (code object attribute), 19 co cellvars (code object attribute), 19 co code (code object attribute), 19 co consts (code object attribute), 19 co filename (code object attribute), 19 co firstlineno (code object attribute), 19 co flags (code object attribute), 19 co freevars (code object attribute), 19 co lnotab (code object attribute), 19 co name (code object attribute), 19 co names (code object attribute), 19 co nlocals (code object attribute), 19 co stacksize (code object attribute), 19 co varnames (code object attribute), 19 code block, 33 object, 19 code block, 55 comma, 38 trailing, 47, 53 command line, 65 comment, 3 comparison, 44 string, 15 comparisons, 22 chaining, 45 compile() (built-in function), 57 complex literal, 9 number, 15 object, 15 complex() (built-in function), 30 compound statement, 59 comprehensions list, 38 constant, 7 constructor class, 21 container, 14, 18 continue

73

statement, 55, 60–62 conversion arithmetic, 37 string, 21, 39, 49 copy() (mapping object method), 26 count() (sequence object method), 26

D dangling else, 59 data, 13 type, 14 type, immutable, 38 datum, 39 dbm (standard module), 16 debugging assertions, 49 decimal literal, 9 DEDENT token, 5, 59 def statement, 62 default parameter value, 62 definition class, 53, 63 function, 53, 62 del statement, 16, 21, 52 delete, 16 deletion attribute, 53 target, 52 target list, 52 delimiters, 10 destructor, 21, 51 dictionary display, 39 object, 16, 18, 22, 39, 40, 51 display dictionary, 39 list, 38 tuple, 38 division, 43 divmod() (built-in function), 28, 29 documentation string, 19

E
EBCDIC, 15 elif keyword, 60 Ellipsis object, 14 else dangling, 59 74

else keyword, 55, 60, 61 empty list, 39 tuple, 15, 38 environment, 33 error handling, 34 errors, 34 escape sequence, 8 eval() (built-in function), 57, 58, 66 evaluation order, 47 exc info (in module sys), 20 exc traceback (in module sys), 20, 61 exc type (in module sys), 61 exc value (in module sys), 61 except keyword, 61 exception, 34, 54 AssertionError, 50 AttributeError, 40 handler, 20 ImportError, 55 NameError, 38 raising, 54 RuntimeError, 53 StopIteration, 53 SyntaxError, 55 TypeError, 43 ValueError, 44 ZeroDivisionError, 43 exception handler, 34 exclusive or, 44 exec statement, 57 execfile() (built-in function), 57 execution frame, 33, 63 restricted, 34 stack, 20 execution model, 33 expression, 37 lambda, 46 list, 46, 49, 50 statement, 49 extend() (sequence object method), 26 extended slicing, 40 extended print statement, 53 extended slicing, 15 extension filename, 55 module, 14

Index

F f back (frame attribute), 19 f builtins (frame attribute), 19 f code (frame attribute), 19 f exc traceback (frame attribute), 20 f exc type (frame attribute), 20 f exc value (frame attribute), 20 f globals (frame attribute), 19 f lasti (frame attribute), 19 f lineno (frame attribute), 20 f locals (frame attribute), 19 f restricted (frame attribute), 19 f trace (frame attribute), 20 False, 14 file object, 19, 66 filename extension, 55 finally keyword, 53, 55, 62 float() (built-in function), 30 floating point number, 15 object, 15 floating point literal, 9 for statement, 54, 55, 60 form lambda, 46, 63 frame execution, 33, 63 object, 19 free variable, 33, 52 from keyword, 55, 56 statement, 33, 56 func closure (function attribute), 16 func code (function attribute), 16 func defaults (function attribute), 16 func dict (function attribute), 16 func doc (function attribute), 16 func globals (function attribute), 16 function anonymous, 46 argument, 16 call, 16, 42 call, user-defined, 42 definition, 53, 62 generator, 53 name, 62 object, 16, 17, 42, 62 user-defined, 16 future Index

statement, 56

G garbage collection, 13 gdbm (standard module), 16 generator function, 17, 53 iterator, 17, 53 object, 19 generic special attribute, 14 get() (mapping object method), 26 global name binding, 57 namespace, 16 global statement, 51, 52, 57 globals() (built-in function), 58 grammar, 1 grouping, 5

H handle an exception, 34 handler exception, 20 has key() (mapping object method), 26 hash() (built-in function), 22 hash character, 3 hex() (built-in function), 30 hexadecimal literal, 9 hierarchical module names, 56 hierarchy type, 14

I id() (built-in function), 13 identifier, 6, 37 identity test, 46 identity of an object, 13 if statement, 60 im class (method attribute), 17 im func (method attribute), 16, 17 im self (method attribute), 16, 17 imaginary literal, 9 immutable data type, 38 object, 15, 38, 39 immutable object, 13 immutable sequence object, 15 import 75

statement, 18, 55 ImportError exception, 55 in keyword, 60 operator, 46 inclusive or, 44 INDENT token, 5 indentation, 5 index operation, 15 index() (sequence object method), 26 indices() (slice method), 20 inheritance, 63 initialization module, 55 input, 66 raw, 66 input() (built-in function), 66 insert() (sequence object method), 26 instance call, 26, 42 class, 18 object, 18, 42 int() (built-in function), 30 integer, 15 object, 14 representation, 15 integer literal, 9 interactive mode, 65 internal type, 19 interpreter, 65 inversion, 43 invocation, 16 is operator, 46 is not operator, 46 item sequence, 40 string, 40 item selection, 15 items() (mapping object method), 26 iteritems() (mapping object method), 26 iterkeys() (mapping object method), 26 itervalues() (mapping object method), 26

keys() (mapping object method), 26 keyword, 6 elif, 60 else, 55, 60, 61 except, 61 finally, 53, 55, 62 from, 55, 56 in, 60

L lambda expression, 46 form, 46, 63 language C, 14, 15, 17, 44 Java, 15 Pascal, 60 last traceback (in module sys), 20 leading whitespace, 5 len() (built-in function), 15, 16, 26 lexical analysis, 3 lexical definitions, 2 line continuation, 4 line joining, 3, 4 line structure, 3 list assignment, target, 50 comprehensions, 38 deletion target, 52 display, 38 empty, 39 expression, 46, 49, 50 object, 16, 39, 40, 51 target, 50, 60 literal, 7, 38 locals() (built-in function), 58 logical line, 3 long() (built-in function), 30 long integer object, 14 long integer literal, 9 loop over mutable sequence, 60 statement, 54, 55, 60 loop control target, 55

J
Java language, 15

M makefile() (socket method), 19 mangling name, 38 mapping object, 16, 19, 40, 51 membership Index

K key, 39 key/datum pair, 39 76

test, 46 method built-in, 17 call, 42 object, 16, 17, 42 user-defined, 16 minus, 43 module built-in, 55 extension, 14 importing, 55 initialization, 55 name, 55 names, hierarchical, 56 namespace, 18 object, 18, 40 search path, 55 user-defined, 55 modules (in module sys), 55 modulo, 43 multiplication, 43 mutable object, 16, 50, 51 mutable object, 13 mutable sequence loop over, 60 object, 16

operator, 46 not in operator, 46 notation, 1 NotImplemented, 14 object, 14 null operation, 52 number, 9 complex, 15 floating point, 15 numeric object, 14, 19 numeric literal, 9

O object, 13 Boolean, 14 built-in function, 17, 42 built-in method, 17, 42 callable, 16, 41 class, 18, 42, 63 class instance, 18, 42 code, 19 complex, 15 dictionary, 16, 18, 22, 39, 40, 51 Ellipsis, 14 file, 19, 66 floating point, 15 frame, 19 function, 16, 17, 42, 62 generator, 19 immutable, 15, 38, 39 immutable sequence, 15 instance, 18, 42 integer, 14 list, 16, 39, 40, 51 long integer, 14 mapping, 16, 19, 40, 51 method, 16, 17, 42 module, 18, 40 mutable, 16, 50, 51 mutable sequence, 16 None, 14 NotImplemented, 14 numeric, 14, 19 plain integer, 14 recursive, 39 sequence, 15, 19, 40, 46, 51, 60 slice, 26 string, 15, 40 traceback, 20, 54, 61 tuple, 15, 40, 47 unicode, 15 77

N name, 6, 33, 37 binding, 33, 50, 55, 62, 63 binding, global, 57 class, 63 function, 62 mangling, 38 module, 55 rebinding, 50 unbinding, 52 NameError exception, 38 NameError (built-in exception), 33 names hierarchical module, 56 private, 38 namespace, 33 global, 16 module, 18 negation, 43 newline suppression, 53 NEWLINE token, 3, 59 None, 14, 49 object, 14 not Index

user-defined function, 16, 42, 62 user-defined method, 16 oct() (built-in function), 30 octal literal, 9 open() (built-in function), 19 operation binary arithmetic, 43 binary bit-wise, 44 Boolean, 46 null, 52 shifting, 44 unary arithmetic, 43 unary bit-wise, 43 operator and, 46 in, 46 is, 46 is not, 46 not, 46 not in, 46 or, 46 overloading, 20 precedence, 47 operators, 10 or bit-wise, 44 exclusive, 44 inclusive, 44 or operator, 46 ord() (built-in function), 15 order evaluation, 47 output, 49, 53 standard, 49, 53 OverflowError (built-in exception), 14 overloading operator, 20

plain integer literal, 9 plus, 43 pop() mapping object method, 26 sequence object method, 26 popen() (in module os), 19 popitem() (mapping object method), 26 pow() (built-in function), 28, 29 precedence operator, 47 primary, 39 print statement, 21, 53 private names, 38 procedure call, 49 program, 65 Python Enhancement Proposals PEP 0255, 54

Q quotes backward, 21, 39 reverse, 21, 39

R raise statement, 54 raise an exception, 34 raising exception, 54 range() (built-in function), 60 raw input, 66 raw string, 7 raw input() (built-in function), 66 readline() (file method), 66 rebinding name, 50 recursive object, 39 reference attribute, 39 reference counting, 13 remove() (sequence object method), 26 repr() (built-in function), 21, 39, 49 representation integer, 15 reserved word, 6 restricted execution, 34 return statement, 53, 61, 62 reverse Index

P packages, 56 parameter value, default, 62 parenthesized form, 38 parser, 3 Pascal language, 60 pass statement, 52 path module search, 55 physical line, 3, 4, 8 plain integer object, 14 78

quotes, 21, 39 reverse() (sequence object method), 26 RuntimeError exception, 53

S scope, 33 search path, module, 55 sequence item, 40 object, 15, 19, 40, 46, 51, 60 setdefault() (mapping object method), 26 shifting operation, 44 simple statement, 49 singleton tuple, 15 slice, 40 object, 26 slice() (built-in function), 20 slicing, 15, 16, 40 assignment, 51 extended, 40 sort() (sequence object method), 26 space, 5 special attribute, 14 attribute, generic, 14 stack execution, 20 trace, 20 standard output, 49, 53 Standard C, 8 standard input, 65 start (slice object attribute), 20, 41 statement assert, 49 assignment, 16, 50 assignment, augmented, 51 break, 54, 60–62 class, 63 compound, 59 continue, 55, 60–62 def, 62 del, 16, 21, 52 exec, 57 expression, 49 for, 54, 55, 60 from, 33, 56 future, 56 global, 51, 52, 57 Index

if, 60 import, 18, 55 loop, 54, 55, 60 pass, 52 print, 21, 53 raise, 54 return, 53, 61, 62 simple, 49 try, 20, 61 while, 54, 55, 60 yield, 53 statement grouping, 5 stderr (in module sys), 19 stdin (in module sys), 19 stdio, 19 stdout (in module sys), 19, 53 step (slice object attribute), 20, 41 stop (slice object attribute), 20, 41 StopIteration exception, 53 str() (built-in function), 21, 39 string comparison, 15 conversion, 21, 39, 49 item, 40 object, 15, 40 Unicode, 7 string literal, 7 subscription, 15, 16, 40 assignment, 51 subtraction, 44 suite, 59 suppression newline, 53 syntax, 1, 37 SyntaxError exception, 55 sys (built-in module), 53, 55, 61, 65 sys.exc info, 20 sys.exc traceback, 20 sys.last traceback, 20 sys.modules, 55 sys.stderr, 19 sys.stdin, 19 sys.stdout, 19 SystemExit (built-in exception), 35

T tab, 5 target, 50 deletion, 52 list, 50, 60 list assignment, 50 list, deletion, 52 79

loop control, 55 tb frame (traceback attribute), 20 tb lasti (traceback attribute), 20 tb lineno (traceback attribute), 20 tb next (traceback attribute), 20 termination model, 35 test identity, 46 membership, 46 token, 3 trace stack, 20 traceback object, 20, 54, 61 trailing comma, 47, 53 triple-quoted string, 7 True, 14 try statement, 20, 61 tuple display, 38 empty, 15, 38 object, 15, 40, 47 singleton, 15 type, 14 data, 14 hierarchy, 14 immutable data, 38 type() (built-in function), 13 type of an object, 13 TypeError exception, 43 types, internal, 19

function call, 42 method, 16 module, 55 user-defined function object, 16, 42, 62 user-defined method object, 16

V value default parameter, 62 value of an object, 13 ValueError exception, 44 values writing, 49, 53 values() (mapping object method), 26 variable free, 33, 52

W while statement, 54, 55, 60 whitespace, 5 writing values, 49, 53

X xor bit-wise, 44

Y yield statement, 53

U unary arithmetic operation, 43 bit-wise operation, 43 unbinding name, 52 UnboundLocalError, 33 unichr() (built-in function), 15 Unicode, 15 unicode object, 15 unicode() (built-in function), 15, 22 Unicode Consortium, 7 UNIX, 65 unreachable object, 13 unrecognized escape sequence, 8 update() (mapping object method), 26 user-defined function, 16 80

Z
ZeroDivisionError exception, 43

Index

Similar Documents

Premium Essay

In Analog Technology, Compare and Contrast the Advantages and Disadvantages of Amplitude Modulation, Frequency Modulation, Phase Modulation, and Quadrature Amplitude Modulation

...Advantages and disadvantages of the following analog modulation techniques: In analog technology, compare and contrast the advantages and disadvantages of amplitude modulation, frequency modulation, phase modulation, and Quadrature Amplitude Modulation Amplitude Modulation When dealing with communication modulation is the process of altering one or more of the three primary parameters of a message signal. Modulation of message signals allow for the signal to be imbedded into a carrier signal that can be physically transmitted. The three primary parameters are amplitude, frequency, and phase. When dealing with analog modulation techniques each one that is used will have advantages and disadvantages. The amplitude modulation (AM) technique is based on the transformation of the highs and lows of a signal wave or its strength. This technique has the advantages of being able to travel long distances by bouncing off of structures as well as the atmosphere. The main disadvantage of this modulation technique is that is highly susceptible to signal interference from other electronic devices and waves creating and unclear signal, these interferences are what is known has noise. Frequency modulation (FM) is that of what its names says it is the altering of the frequency of a baseband signal. Altering the number of times each second that the current changes direction; comes with the advantage of being less susceptible to noise unlike that of AM. Also unlike AM, FM is not...

Words: 729 - Pages: 3

Free Essay

Team Paper

...In analog technology, compare and contrast the advantages and disadvantages of amplitude modulation, frequency modulation, phase modulation, and Quadrature Amplitude Modulation (QAM). Refrences: Electronics and Radio Today. (n.d.). Retrieved from http://www.electronics-radio.com/articles/radio/modulation/amplitude_modulation/am.php Electronics and Radio Today. (n.d.1). Retrieved from http://www.electronics-radio.com/articles/radio/modulation/frequency_modulation/fm.php M.S. Richer. (2006). Advantages/disadvantages/applications of various Modulation Schemes [Multimedia]. Retrieved from M.S. Richer, http://www-ee.uta.edu/dip/Courses/EE4330/comparison%20of%20modulation%20methods.pdf website. Radio-Electronics.com. (n.d.). Retrieved from http://www.radio-electronics.com/info/rf-technology-design/modulation-techniques/itu-designations-types-of-radio-emissions-transmissions.php Amplitude Modulation Amplitude modulation (AM) is a technique used in electronic communication. The most common use for this is in radio. AM works by varying the strength of the transmitted signal in relation to the information being sent ("Electronics and Radio Today", n.d.). Advantages: There are several advantages of amplitude modulation, and some of these reasons have meant that it is still in widespread use today. It is simple to implement, it can be demodulated using a circuit consisting of very few components, and AM receivers are very cheap as no specialized components are needed...

Words: 985 - Pages: 4

Free Essay

Phase Modulation

...Phase Modulation Phase Modulation “is used in many applications to carry both analogue and digital signals. Keeping the amplitude of the signal constant, the phase is varied to carry the required information or signal” (Poole, Radio-Electronics.com). An advantage of phase modulation is that it is easier compared to Frequency modulation. A Phase modulator is used in determining velocity of moving targets by extracting Doppler information. Doppler information needs a stable carrier which is possible in phase modulation but not in frequency modulation. A disadvantage of Phase modulation is that a frequency multiplier is needed in order to increase Phase modulation. Quadrature Amplitude Modulation Quadrature Amplitude Modulation or QAM is a form of modulation which is widely used for modulating data signals onto a carrier used for radio communications. It is widely used because it offers advantages over other forms of data modulation such as PSK, although many forms of data modulation operate alongside each other. “QAM is a signal in which two carriers shifted in phase by 90 degrees are modulated and the resultant output consists of both amplitude and phase variations. In view of the fact that both amplitude and phase variations are present; it may also be considered as a mixture of amplitude and phase modulation” (Poole, Radio-Electronics.com). There are more disadvantages with QAM then there are advantages. One disadvantage is it is more susceptible to noise because the states...

Words: 332 - Pages: 2

Free Essay

Analog and Digital Comparison Paper

...prime example of a telecommunication that uses this form of conversion is a telephone modem. Voice communications vary in range and are not in binary form, so these analog signals must be translated into digital signals. Digital to analog conversions or DAC is the conversion of binary code to analog signal. In order words, signals having few defined levels or states are converted into signals having a theoretically infinite number of states (Rouse, 2005). Going from digital to analog can sometimes be tricky and even cause the quality of the signal to be compromised. An example of digital to analog conversion would be the use of Internet via a modem; the modem converts computer signals (digital) using standard phone lines. Amplitude Modulation &...

Words: 1984 - Pages: 8

Premium Essay

Pro Wycliff

...n Analog Technology, Compare and Contrast the Advantages and Disadvantages of Amplitude Modulation, Frequency Modulation, Phase Modulation, and Quadrature Amplitude Modulation Advantages and disadvantages of the following analog modulation techniques: In analog technology, compare and contrast the advantages and disadvantages of amplitude modulation, frequency modulation, phase modulation, and Quadrature Amplitude Modulation Amplitude Modulation When dealing with communication modulation is the process of altering one or more of the three primary parameters of a message signal. Modulation of message signals allow for the signal to be imbedded into a carrier signal that can be physically transmitted. The three primary parameters are amplitude, frequency, and phase. When dealing with analog modulation techniques each one that is used will have advantages and disadvantages. The amplitude modulation (AM) technique is based on the transformation of the highs and lows of a signal wave or its strength. This technique has the advantages of being able to travel long distances by bouncing off of structures as well as the atmosphere. The main disadvantage of this modulation technique is that is highly susceptible to signal interference from other electronic devices and waves creating and unclear signal, these interferences are what is known has noise. Frequency modulation (FM) is that of what its names says it is the altering of the frequency of a baseband signal. Altering...

Words: 342 - Pages: 2

Free Essay

A Comparison of Digital and Analog Technologies

...Introduction Analog-to-Digital and Digital-to-Analog Conversions Telecommunications relies on the transmission of data through different mediums such as a telephone, radio, television, among others. These transmissions are done through two signal types, which are analog and digital. Analog is the first type of transmission type because it is the older and has been around for a lot longer than digital. On the other hand, even though digital transmission is a younger generation, it is currently use in more devices than analog. Each signal has its advantages and disadvantages, but in most scenarios, both need to work together to create an effective transmission. Technologies that convert analog into digital and vice-versa have been created for this purpose. Converting the signals allows for a more cohesive environment because each can be adjusted to work on devices or mediums not made for them originally. The next part of this paper covers the technologies use to convert these signals. Analog to Digital Conversion In order for this conversion to take place, an analog-to-digital converter (ADC) is necessary. This component is essential because it is responsible for receiving the analog signal as input and sending a digital signal as output. The ADC receives an analog signal such as sound, voice, or voltage and transforms that signal into a binary output. This output is the digital signal that has a state of either on, which is represented by 1 or an off state represented by 0...

Words: 1049 - Pages: 5

Free Essay

Comparison of Analog and Digital Technology

...followed by the modulation and then reception at the receiver and making sure that there is no factor of signal degradation and noise. “The binary signal is made up of two symbols namely binary digits or bits 1 and 0. If there is no influence of noise and distortion during transmission, the binary information will be the same. The change in the signal is being measure at the receiver. Encoding is needless if the information to be transferred has already been converted in binary form just like in data communications. In contrary, voice communication through telephone is not in binary form. These are analog signals that vary in range of values and therefore must be converted to digital form before it is being used in digital communications system.” (T. T. (2011). Digital signal to analog signal conversions involve the use of DAC (Digital-to-Analog Converters). DAC accepts the discrete binary values and converts them into continuously-varying values of analog signal. This conversion may affect the fidelity of the signal if the process was not properly monitored. Analog telephone lines, most commonly called POTS lines, uses separate lines (e.g. standard phone and fax lines, alarm lines, etc.) from the digital equipment lines (e.g. PBX). The use of modem for computer’s connection to the internet is one of the best examples of conversion from analog to digital signals using standard phone line. Advantages and Disadvantages of Common Modulation Techniques ...

Words: 2102 - Pages: 9

Premium Essay

Team Week 2

...Analog and Digital Comparison Paper Current technology utilizes many different types of transmission cable such as fiber optics, coaxial cable, and twisted pair copper wire. These different types of cables use different communications techniques that maximize their efficiency. For instance, fiber optics can carry digital signals over long distances without amplification or repeaters required. Copper wire, on the other hand, carrying analog signals requiring amplification and noise corrections along the way in much shorter intervals. The result is there is a mix of transmission lines that require special software and equipment such as codecs and modems to convert and move data from one point to another. Codecs and Modems The most common form of analog to digital conversions uses multiplex devices and coder-decoder devices otherwise known as codecs. These programs receive analog signals from sine waves such as audio communications and code them as digital signals. These signals then travel to other locations with codec or modem devices that decode or decompress the data back to analog signals. Digital devices use modems or combinations of codecs and modems to modulate the data signals to analog signals to travel to other modems for demodulation back to digital data. The codec is “software that is used to compress or decompress a digital media file, such as a song or video” (Microsoft, 2014). This process is the same in telecommunications systems, which consist of the encoder...

Words: 2307 - Pages: 10

Free Essay

Team Week 2

...Analog and Digital Comparison Paper Current technology utilizes many different types of transmission cable such as fiber optics, coaxial cable, and twisted pair copper wire. These different types of cables use different communications techniques that maximize their efficiency. For instance, fiber optics can carry digital signals over long distances without amplification or repeaters required. Copper wire, on the other hand, carrying analog signals requiring amplification and noise corrections along the way in much shorter intervals. The result is there is a mix of transmission lines that require special software and equipment such as codecs and modems to convert and move data from one point to another. Codecs and Modems The most common form of analog to digital conversions uses multiplex devices and coder-decoder devices otherwise known as codecs. These programs receive analog signals from sine waves such as audio communications and code them as digital signals. These signals then travel to other locations with codec or modem devices that decode or decompress the data back to analog signals. Digital devices use modems or combinations of codecs and modems to modulate the data signals to analog signals to travel to other modems for demodulation back to digital data. The codec is “software that is used to compress or decompress a digital media file, such as a song or video” (Microsoft, 2014). This process is the same in telecommunications systems, which consist of the encoder...

Words: 2307 - Pages: 10

Free Essay

Ese 576 Final Project Report

...ESE 576 Final Project Report ESE 576 Digital Communication System Final Project Report Learning of Gaussian Minimum Shift Keying Carrier Modulation (GMSK) Name: XX ESE 576 Final Project Report Content (1). Background and Motivation: ............................................................... 3 1. FSK:....................................................................................................... 3 2. CPFSK/CPM: ......................................................................................... 3 3. MSK:............................................................................................. 3 4. GMSK: ................................................................................................... 3 (2). Theoretical Analysis:........................................................................... 4 1 CPM:....................................................................................................... 4 2.CPFSK 3. MSK: ...................................................................................................... 5 4. GMSK: ................................................................................................... 5 (3). Simulation and Interpretation: ............................................................. 5 1. Modulation:.......................................................................................... 6 2. Demodulation: ...............................................................

Words: 1587 - Pages: 7

Free Essay

Technology

...•        What are the various modulation techniques? Begin your explanation with frequency-shift keying and move to multilevel QAM.   During this week’s readings I have found 4 different modulation techniques:   Amplitude modulations, frequency modulation, phase modulation, and quadrature amplitude modulation.  While these have different modulation schemes that branch out, these are the primary used modulations I have found. Amplitude modulation is when different amplitudes are used to represent the digital bitstream in analog format.    Modems rely on amplitude modulation to determine the high amplitude that is represented by ones and low amplitudes that are represented by zeros.  They also rely on amplitude modulation to determine the difference in the amplitudes so the receiving device can put out the message in the correct way.  Frequency modulation is also known as FSK, or frequency-shift key.  FSK’s uses two different frequencies to distinguish between a mark digital 1 and a space digital 0 when transmitting on an analog line.  It is used on modems that operate at 1,200bps or slower (Goleniewski, 2007).       Phase modulation modifies a sine wave, also known as a carrier, to allow it to carry information.  The phase of the sine wave is changed to fit the type of information that is being transferred.  Phase modulation can be paired with carrierless amplitude for ADSL, or Asymmetrical DSL. Last Quadrature Amplitude Modulation is a “single-carrier scheme that modulates...

Words: 940 - Pages: 4

Free Essay

Modulation

...Introduction Modulation is the process of encoding information from a message source in a manner suitable for transmission.It involves translating a baseband message signal to a bandpass signal at frequencies that are very high compared to the baseband frequency. Baseband signal is called modulating signal.Bandpass signal is called modulated signal. In telecommunications, modulation is the process of conveying a message signal, for example a digital bit stream or an analog audio signal, inside another signal that can be physically transmitted. Modulation of a sine waveform transforms a baseband message signal into a passband signal. A modulator is a device that performs modulation. A demodulator  is a device that performs demodulation, the inverse of modultion. A modem (from modulator–demodulator) can perform both operations. Types of modulation • Analog modulation • Digital modulation Analog modulation- The aim of analog modulation is to transfer an analog baseband (or lowpass) signal, for example an audio signal or TV signal, over an analog bandpass channel at a different frequency, for example over a limited radio frequency band or a cable TV network channel. • Digital modulation The aim of digital baseband modulation methods, also known as line coding, is to transfer a digital bit stream over a baseband channel, typically a non-filtered copper wire such as a serial bus or a wired local area network. AMPLITUDE MODULATION(AM) ...

Words: 2983 - Pages: 12

Free Essay

Analog and Digital Comparison

...Analog and Digital Comparison Technologies for analog-to-digital and digital-to-analog conversions There is no actual all analog or all digital telecommunications going on technologically today (Goleniewsk & Wilson Jarrett, 2007, Chapter Chapter 1, Analog Versus Digital Transmission). One day, developers hope to make the network 100% digital. Connecting to the internet or just making a call to your mother two states over is a mixture of both when it comes to communicating from one terminal to the next. That being said, it takes codecs and modems for a successful conversion to occur. Say you are calling another state from a land line. This call will start out analog at your telephone and then must be converted to digital. When you pick your phone up, it connects to a codec. Your voice can range from 100Hz to 10,000Hz depending on many factors. The average Hz a phone company will allot is 4,000 which works for virtually all people. Codec is short for coder-decoder and it works by minimizing the amount of bits per second that will carry the voice to the multiplexer. In the case of a cellular network, the data will have to be compressed even further so that the most efficient transmission can occur. The codec will then transfer the data to a multiplexer. This particular multiplexer is a TDM (time division multiplexer). This will allow for one channel to be open at a time. This does make sense since it would not be good to take over a phone line once it is being...

Words: 1772 - Pages: 8

Premium Essay

Analog Comparrison

...transmitted digitally. Compression is required when converting cell phone networks and video communications because of the limited spectrum and channels (Goleniewski & Jarret, 2007). A modem controls analog signals to encode digital data and demodulates the signal to decode the information sent. An analog signal works with computers to transform the digital data into electrical signals through a telephone channel and then demodulate the signals back into digital data. However, conversions have been known to cause malfunctions in the network so it is best to have end-to-end digital and end-to-end optical networks. Analog technology consists of amplitude modulation, frequency modulation, phase modulation, and Quadrature Amplitude Modulation (QAM). There advantages and disadvantages to each one. Advantages to amplitude modulation include effortlessness to execute, it can be demodulated with a circuit consisting of hardly any components, and...

Words: 544 - Pages: 3

Free Essay

Checkpoint Week 2

...Voltage of my mountain analogy is described through the air pressure that is generated from each of the mountains. The current will be the air flow rate that flows from mountain to mountain. Diameter of the mountain will be the resistance and the electrical power will come from the total amount of air that is between each mountain. Analog Modulation are generally use by radio stations and there are 3 types of analog modulation. The first type is amplitude modulation and the higher wave will be 1 bit while the lower wave will be 0 bit. Example if this is below: [pic] The next modulation is called phase modulation and this phase change the starting point of the cycle. These changes happens when the 1 bit to a 0 bit are being transmitted. An example of this is below. [pic] Digital modulation is used in most wireless devices and digital modulation is used more because digital has a lot more advantages over analog modulation. Some of these advantages are better use of bandwidth, less power to transmit, and performs better when other signals interfere. Below is my analogy of digital modulation in a binary modulation of frequency shift keying. [pic] ----------------------- 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 -...

Words: 286 - Pages: 2