Python 2 v/s 3 | Important Diff B/w Python 2 and3 with examples

Python-2-vs-python-3

Most of the beginners have confusion to decide between Python 2 and 3. I would just say, check the complete details regarding both the versions and then conclude which version to use. Get the differences between both the versions of Python. Know the brief details regarding python 2 vs 3 in the below sections.

Python-2-vs-python-3

Python 2 vs 3

Python 3 was developed as a result to fix all the problems present in Python 2. These changes meant that Python 3 was not compatible with Python 2. It means that Python 3 did not carry the problems of Python 2. Some aspects of version 3 were back ported to Python 2.6 and 2.7 to make migration to Python 3 easier.

The below given differences gives you a clear idea of which version to use. But what if you are on the track of a new project and have to pick one of them? No worries!! even in that case there is currently no right or wrong. Because Python 2.7.x and Python 3.x support the libraries that you  are planning to use. But make sure that you know the differences (Python 2 vs 3) between these two versions to avoid common mistakes while writing the code.

Why Python 3?

If you ask a question of why Python 3? Read this article completely, you will get the perfect answer for that!! As the Python 2 has been end of life’d, the programmers who work on Python have decided that there won’t be any Python 2.8. They have also decided that Python 2.7 will only get security updates from Python 3 development branch. No new features are added unless someone spends the extra time to back port them. Therefore, amazing future module full Python 3 version is released. Check the below sections to get the solution for your question of Python 2 vs 3.

Differences between Python 2 and 3

The main differences between python 2 and 3 are as follows.

  • print function
  • Unicode
  • Division operator
  • xrange
  • Error Handling
  • _future_ module
  1. Print Function

Python 2’s print statement is replaced by print() function, it means that we have to wrap the object we want to print in parantheses. The version Python 2 does not have any problem with additional parantheses, but Python 3 would raise a syntax error if we call the print function.

Python 2
print ‘Python’, python_version()
print ‘Hello, World!’
print(‘Hello, World!’)
print “text” print additionally text on the equivalent line’

Output: Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

print(‘Python’, python_version())
print(‘Hello, World!’)
print(“some text,”, end=””)
print(‘ print more text on the same line’)

Output: Python 3.4.1
Hello, World!
print additional text on the equivalent line

2. Unicode

Python 2 has separate unicode(), ASCII str() types but no byte type. But in Python 3, Unicode (utf-8) strings and 2 byte classes: byte and bytearrays are included.

Python 3 Example

print(type(‘default string ‘))
print(type(b’string with b ‘))
”’
Output of Python 2.x (Bytes is same as str)
<type ‘str’>
<type ‘str’>

Output of Python 3.x (Bytes & str are different)
<class ‘str’>
<class ‘bytes’>
”’

Example of Python 2
print(type(‘default string ‘))
print(type(u’string with b ‘))
”’
Output of Python 2.x (Unicode and str units are different)
<type ‘str’>
<type ‘unicode’>

Output of Python 3.x (Unicode and str are same)
<class ‘str’>
<class ‘str’>

3. Division Operator

If we execute our code or port our code of python 3.x in python 2.x, it would be dangerous in the case if integer division changes go unnoticed(since error is not raised). It is always preferred to use the floating value like 7.0/5 or 7/5.0) to get the expected output while porting the code.

Example of Python 2

print ‘Hello, Geeks’ # Python 3.x doesn’t support
print(‘Hope You like these facts’)
”’
Output in Python 2.x :
Hello, Geeks
Hope You like these facts

Output in Python 3.x :
File “a.py”, line 1
print ‘Hello, Geeks’
^
SyntaxError: invalid syntax

4. xrange

xrange() of version Python 2.x doesn’t exist in Python 3.x. In the version Python 2.x, the range return a list i.e., range(4) returns [0,1,2,3]. The iterator which works same as Java Iterator and generates number are available i.e., xrange(4) returns iterator object (xrange returns a xrange object). We prefer range() as range provides a static list, if we need to iterate the same sequence multiple times.

To reconstruct the sequence every time xrange() is used. This method doesnot support other list methods and slices. The main advantage of xrange() is, it saves more memory when each task is to iterate over a large range. The range function in Python 3 is the functionality of xrange in Python 2.x. Therefore, to keep our code portable, we need to use range instead of xrange.

Example:

for x in xrange(1, 5):
print(x),
for x in range(1, 5):
print(x),
”’
Output in Python 2.x
1 2 3 4 1 2 3 4

Output in Python 3.x
NameError: name ‘xrange’ is not defined

5. Error Handling

There are changes regarding error handling techniques in both the versions. In the version python 3.x, ‘as’ keyword is required. This is one of the difference of Python 2 vs 3.

Example

try:
trying_to_check_error
except NameError, err:
print err, ‘Error Caused’ # Would not work in Python 3.x
”’
Output in Python 2.x:
name ‘trying_to_check_error’ is not defined Error Caused

Output in Python 3.x :
File “a.py”, line 3
except NameError, err:
^
SyntaxError: invalid syntax
”’

Example using “as” keyword
try:
trying_to_check_error
except NameError as err: # ‘as’ is needed in Python 3.x
print (err, ‘Error Caused’)
”’
Output in Python 2.x:
(NameError(“name ‘trying_to_check_error’ is not defined”,), ‘Error Caused’)

Output in Python 3.x :
name ‘trying_to_check_error’ is not defined Error Caused

6. _future_module

There is no major difference between two versions, but most of the useful thing to tell is that the idea_of_future module is to help in migration. If Python 3.x wants to support 2.x code, then you should use _future_imports it in our code.

# In below python 2.x code, division works
# same as version Python 3.x because we use __future__
from __future__ import division

print 7 / 5
print -7 / 5

Output:1.4

-1.4

Performance of Python 2 & 3

In the version Python 3, the performance issues have been upgraded. If the benchmarks are to compared, the changes are negligible. Know the performance of both the versions and choose one among Python 2 vs 3.

Python 2

  • print() functional brackets optional.
  • Raw_input () reads string.
  • generator .next().
  • Prefix string with u to make unicode string.
  • Division of integers always return integer – 5/2=2.
  • input() evaluates data read.

Python 3

  • Python 2 to Python 3 utility.
  • Cannot use comparison operators on non natural comparisons.
  • print() functional brackets compulsory.
  • String unicode by default.
  • Input always reads string.
  • Next (generator).
  • Dictionary .keys() and .values() returns a view not a list.
  • Division of integers can lead to float – 5/2=2.5.
  • Raw_input() not available.
    Eg. None < None will be a TypeError caused instead of returning false.
  • Percent string operator which is formatted is detracted use the format Function or concatenation.

For the new beginners, who want to learn programming in Python language is best to go for Python 3. It is intuitive and diverse language where ton of companies are using it. The new individuals who want to learn Python can get the best Python Online Training in Hyderabad from here. We will provide you the further information regarding all the details of the language. If you have any queries regarding python 2 vs 3 comment us in the below sections.

Leave a Reply

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