Difference between Python 2 and 3

Here you will know about difference between python 2 and 3.

As a newbie, everyone confuses that which version of Python should learn and use (Python 2.x or 3.x, where x means versions). Let’s see the key differences between them.

Python 2 vs 3 - Difference between Python 2 and 3

Image Source

Python 2 vs 3 – Difference between Python 2 and 3

  Python 2 Python 3
1. Integer Division print 9/2

>> 4

print(9/2)

>> 4.5

2. Print function print “Hello world”

>>Hello world

print(“Hello world”)

>>Hello world

3. Unicode print type(Unicode(“Hello”))

>>  <type ‘unicode’>

 

print type(b’Hello’)

>> <type ‘str’>

 

print ‘hello’ +  b’ world’

>>hello world

 

print type(bytearray(b’hello world’))

>> <type ‘bytearray’> 

print (‘\u03BCnico\u394e!’)

>> µnico∆e!

 

print(type(b’hello’))

>> <class ‘bytes’>

 

print(‘hello’ + b’ world’))

>> TypeError

 

print(type(bytearray(b’hello’)))

>> <class ‘bytearray’>

4. xrange function Support range() and xrange() both. have no xrange() function but range() function will behave like xrange() in python 2.
5. Raising exception raise IOError, “file not found”

>>IOError: file not found

raise IOError(“file not found”)

>>IOError: file not found                           

6. Handling exception try:

  print 4/0

except ZeroDivisionError, err:

  print “can’t divide by zero”

  print “error – “ + err

output:

can’t divide by zero

error – integer division or modulo by zero

try:

  print(4/0)

except ZeroDivisionError as err:

  print(“can’t divide by zero”)

  print(“error –“ + str(err))

output:

can’t divide by zero

error – division by zero

7. Leak of for-loop variables in global namespace i = 1

print ‘before: i = ‘, i

print ‘loop:’,[i for i in range(5)]

print ‘after:i = ‘, i

Output:

before: i =1

loop: [0,1,2,3,4]

after: i = 4

i = 1

print(‘before :i =’, i)

print(‘loop:’ [i for i in range(5)])

print(‘after: i = ‘, i)

Output:

before: i = 1

loop: [0,1,2,3,4]

after: i = 1

8. .next() method have next() function and .next() method for iterate next element.

list1 = [4, 43, 34,  32]

iterator = iter(list1)

print iterator.next()

print next(iterator)

print iterator.next()

Output:

4

43

34

Have only next() function.

list1 = [4, 43, 34, 32]

iterator = iter(list1)

print (next(iterator))

print (next(iterator))

print (next(iterator))

Output:

4

43

34

9. input() method We can use both raw_input() and input() method.

s = raw_input(“enter something:”)

raw_input() is replaced by input() method. There is no raw_input() method.

s = input(“enter something:”)

Let’s understand these differences in detail.

1. Integer Division:-

In python 2 if we perform division on two integers then the output will be an integer too. But in python 3, output will be accurate, so the result can be in float too. Still want the result in integer, then you can use print(9//2) it return an integer result.

2. Print Function:-

In python 2 parenthesis aren’t compulsory to use we can print anything without using parenthesis but in Python 3 it is compulsory to use parenthesis otherwise it will raise error.

3. Unicode:-

Python 2 has ASCII str() Types, separate Unicode but it doesn’t have byte type.

But in Python 3 we have Unicode (utf-8: 8 means it uses 8-bit block to represent a character) strings and also 2 byte classes that are bytearray and byte.

Python 2 treats string and bytes as same, so we can also concatenate them. But in Python 3 we can’t concatenate a byte array with strings, because both are different for python 3.

4. xrange function:-

python 2 has two handy function for creating a range of integers  that is used in for loop, these are range and xrange. They both provide a way to generate a list of integers. So for the most part, xrange and range are the exact same in terms of functionality. The only difference is that range returns a Python List object and xrange returns an xrange object. range function creates an array of integers, so it will take much memory if we create a range of millions, which can result MemoryError and crash your program. So xrange is the function to use if you’ve a really memory sensitive system such as cell phone.

But in python 3 there is no xrange function, the range function will work as xrange in python 2.

Example:

#program in python 3

for i in range(1,10):

  print(i)

#program in python 2

for i in xrange(1,10):

  print i

Output

1

2

3

4

5

6

7

8

9 

5. Raising exception:-

as we’ve seen the difference between print function, raising an exception will follow the same syntax.

In python 2, its

raise IOError, “file not found”

In python 3, its

raise IOError(“file not found”)

6. Handling exception:-

there is a minor change in syntax, we’ve to use as keyword in python 3.

In python 2, its

except IOError, err:

In python 3, its

except IOError as err: 

7. Leak of for-loop variables in global namespace:-

In python 2 there was a problem that value of a global variable had changed while using that variable in for-loop.

But in Python 3, for loop variables don’t leak into the global namespace anymore!

8. .next() method:-

Python have .next() method and next() function to fetch the next element of an iterator.

But in python 3 .next() method is no more. We have to use only next() function to iterate the next element of iterator.

9.input() method:-

python 2 have input() and raw_input() methods for taking input. The difference between them raw_input() returns a string, and input() tries to run the input as a python expression.

Mostly all we want the string as input then we convert it into any datatype as we want.

In python 3 there is no raw_input() method. The raw_input() method is replaced by input() in python 3. If you still want to use the input() method like in python 2 then we can use eval() method.

eval(input(“enter something:”))

it will work as same as input() in python 2.

There are many other differences between python 2 and python 3 like

10. The __future__ Module:-

as we know there are many things that python 3 supports but python 2 don’t. if you’re planning python 3 support for your code then use __future__ module.

Let’s say we want python 3’s integer division behavior in our python 2 program then our program will look like

from  __future__ import division

print 9/2

output:

4.5

without __future__ module

Print 9/2

Output:

4 

11. Libraries:-

The advantage to use python 2 is it have a large number of libraries. Python 2 is still the default in many operating systems like ubuntu 14.04 and 16.04 LTS. But python 3 is also developing day by day, all the future developments will be implement in python 3 rather than the python 2.

So if you’re completely beginner then we recommend python 3 because it is the future of Python and it is easy as python 2 to learn and python 3 has some additional features (eg. Function memoiziation).

Comment below if you have queries related to above tutorial for difference between python 2 and 3.

3 thoughts on “Difference between Python 2 and 3”

  1. i was here just to complete my assignment but learned a lot too because language( of the article) is so easy to understand . thanks for this Sir. Keep posting

  2. What was the date of this article? Many of the Python 2 versus 3 articles are written a few years ago, and I am not sure how much the Python 3 support has increased over the last few years? Ultimately, even if Version 2 was better due to more support, the question should be what will the future migration for all platforms become? Do we believe that the programming world will continue with two separate versions, or do we see one of the versions becoming dominate in the coming years?

    And thank you for this post! Excellent article!

Leave a Comment

Your email address will not be published. Required fields are marked *