# What has to be modified when switching to Python 3.x?

The book Computing with Python was written based on Python 2.7 but already pointing out some differences to Python 3.x. Here we collect changes in the example and text, which have to be considered when you use the book in connection with Python 3.4 (or higher).

## Affected Sections (Summary):

(details below)

• print command: --

• execfile replacement: Ch. I.4, II.6, II.6.2, XII.3.2 (Example 5)
• range: Ch. II.2.4 (p.8), Ch. IV.1 (p. 30 on two places), Ch. IV.1.1 (p. 32, p. 33)
• xrange: replace all occurences of xrange by range
• zip: Ch. IV.1.5 (p. 35), Ch. 10.7 (p. 149, Exercise 8)

## The print command

The print command is in Python 3.x a function and has always to be written with "(..)". This allows to give the print command arguments, such a seperator string, an end string

In [1]:
a = 3
b = 4
print(a,b,a+b,sep='...',end=' end \n.\n.')

3...4...7 end
.
.


another parameter of print is a file object.

## The execfile command

This built-in command is no longer available in Python 3.x.

Let us first generate a file with Python commands in it

In [2]:
fi=open('myfile.py','w')
fi.write('print(3+4)')
fi.close()


The simplest form of a replacement for execfile is

In [3]:
exec(open('myfile.py').read())

7



This change affects Ch. I.4, II.6, II.6.2, XII.3.2 (Example 5)

## The range command

The range command returns in Python 3 a generator and not a list. Many commands can have lists or generators as arguments (e.g. meshgrid, polyfit,array). Consequently, only few examples in the book are affected by this change.

This makes xrange obsolet.

To obtain with range a list one hast to apply the command list to the result of range:

In [4]:
a=range(3)
print(a)

range(0, 3)


In [5]:
a=list(range(3))
print(a)

[0, 1, 2]



This change affects all occurences of xrange. Replace xrange by range everywhere in the text where it occurs

Change range(...) to list(range(...)) on the following pages

Ch. II.2.4 (p.8), Ch. IV.1 (p. 30 on two places), Ch. IV.1.1 (p. 32, p. 33)

Example:

Change:

In [6]:
L=range(4)


to

In [7]:
L=list(range(4))


## The zip command

The zip command returns in Python 3 a generator and not a list. To obtain a list from zip, one has to apply list(..) to its result:

In [8]:
list(zip([1,2,3],['a','b','c']))

Out[8]:
[(1, 'a'), (2, 'b'), (3, 'c')]


This affects the following places in the book:

Ch. IV.1.5 (p. 35), Ch. 10.7 (p. 149, Exercise 8)

You may also want to replace all itertool.izip by zip