Using This Book with Python 3

As this book went to press, Python 3 was released (see for details). The code examples used in the book are compliant with Python 2.5 through 2.7 but many of them will not run under Python 3. The most important changes are listed below. These changes will be included in future printings of the book.

Terminal Output

print is now a function name rather than an operator. Thus, the data to be printed must be listed within parentheses. The arguments to print must be strings, so data of other types must be converted using the str function before they are output. Examples:

Python 2.x
Python 3.x
print "hello world!" print("Hello world!")
print math.pi print(math.pi)
print "Area:", area print("Area:", area)
print "No new line", print("No new line", end = "")
print print()

Terminal Input

input is now used for all terminal inputs. This function behaves like the old raw_input function, so it returns a string. Thus, strings of digits must be converted to numbers using the function int or float after input. Examples:

Python 2.x
Python 3.x
name = raw_input("Enter your name: ") name = input("Enter your name: ")
age = input("Enter your age: ") age = int(input("Enter your age: "))
pi = input("Enter the value of pi: ") pi = float(input("Enter the value of pi: "))

Integer Division

The / operator now produces a float when used with two integer operands. To obtain an integer quotient, you must now use the // operator. Examples:

Python 2.x
Python 3.x
7 / 2 # Returns 3 7 // 2 # Returns 3
7 / 2.0 # Returns 3.5 7 / 2 # Returns 3.5

Loops with xrange

The xrange function has been discontinued, and the range function now behaves like xrange. Examples:

Python 2.x
Python 3.x
for count in xrange(10): print count for count in range(10): print(count)
range(10) # Returns a list from 0 through 9 list(range(10)) # Returns a list from 0 through 9

Comparisons of Objects with the cmp Function

The cmp function and the __cmp__ method have been discontinued. Thus, you must implement the methods __eq__, __gt__, and __lt__ to support the comparisons of new classes of objects used in the sorting of lists.

Dictionary Methods keys, values, and items Do Not Return Lists

The methods keys, values, and items in the dict class return views (similar to iterators) instead of lists. Examples:

Python 2.x
Python 3.x
for key, item in aDictionary.items(): 
    print key, item 
for key, item in aDictionary.items(): 
    print(key, item)
keys = aDictionary.keys()
for key in keys: 
    print key, aDictionary[key] 
for key in sorted(aDictionary): 
    print(key, aDictionary[key]) 

The map and filter Functions Now Return Iterators

The function map and filter return iterators rather than lists. Examples:

Python 2.x
Python 3.x
results = map(abs, [4, 10, -22, -44])
results = list(map(abs, [4, 10, -22, -44]))