Differences between Python 2.7 and Python 3

The well-known differences between Python 2.7 and Python 3 is the famous print function. While in some widely-used machine-learning like tensorflow and PyTorch, the print functions are regulated to the same form. At these circumstances, how can we tell the big version quickly from the codes without sometime putting a great effort to install a version of Python 3 only to find that it is run on version 2.7.

Definition of class

the definition of the super inherited function differs:

1
2
3
4
5
6
7
8
9
#!/usr/bin/pyhon3
class MyParentClass(object):
def __init__(self, arg):
pass

class MyClass(object):
def __init__(self, arg):
MyParentClass.__init__(self, arg)
self.arg = arg
1
2
3
4
5
6
7
8
9
#!/usr/bin/python27
class MyParentClass(object):
def __init__(self, arg):
pass

class MyClass(object):
def __init__(self, arg):
super(MyClass, self, arg).__init__()
self.arg = arg

rounding operation

The / operation for integers in Python2.7 is by default the rounding operation.

1
2
#!/usr/bin/python27
print(3/2) # will give the result: 1

In Python 3, you should do this as equivalence:

1
2
3
#!/usr/bin/python3
print(3/2) # will give the result 1.5
print(3//2) # will give the result 1

str format

The old style is something like

1
'%d %d' % (1, 2)

output:1 2

The new style:

1
'{} {}'.format(1, 2)

output:1 2

The new style allows re-arranging:

1
'{1} {0}'.format(1,2)

output:2 1

pickle package

Before Python 3, one should import cPickle as pickle. Python3 integrated pickle for object serialization.

Encoding:

py2, default latin1: pickle.load(f)
py3, default utf-8: pickle.load(f, encoding=’latin1’)

xrange

In python2, xrange()
Python3 range()

Understanding Python package installation from pip or conda or Linux distro package manager Vim config file on Linux desktop

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×