Python 2-to-3 Tips

This is a short post to help those of you who need help translating code from Python 2 to Python 3.

Python 2 is the most popular Python version (at least at this time and certainly at the time my courses were created), hence why it was used.

It comes with Mac OS and Ubuntu pre-installed so when you type in “python” into your command line, you get Python 2.

This list is not exhaustive. It shows only code that appears commonly in my machine learning scripts, to assist the students taking my machine learning courses (https://deeplearningcourses.com).

 

Integer Division

OLD:

a / b

NEW:

a // b

 

For Loops

OLD:

for i in xrange

NEW:

for i in range

 

Printing

OLD:

print "hello world"

NEW:

print("hello world")

 

Dictionary iteration

OLD:

for k, v in d.iteritems():

NEW:

for k, v in d.items():

COMPATIBLE WITH BOTH:

from future.utils import iteritems
for k, v in iteritems(d):