Open In App

Important differences between Python 2.x and Python 3.x with examples

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples.

Differences between Python 2.x and Python 3.x

Here, we will see the differences in the following libraries and modules:

Python Division operator

If we are porting our code or executing python 3.x code in python 2.x, it can be dangerous if integer division changes go unnoticed (since it doesn’t raise any error). It is preferred to use the floating value (like 7.0/5 or 7/5.0) to get the expected result when porting our code.  For more information about this you can refer to Division Operator in Python.

Python3




print(7 / 5 )
print(-7 / 5)    
'''
Output in Python 2.x
1
-2
 
Output in Python 3.x :
1.4
-1.4
'''


Print Function in Python

This is the most well-known change. In this, the print keyword in Python 2.x is replaced by the print() function in Python 3.x. However, parentheses work in Python 2 if space is added after the print keyword because the interpreter evaluates it as an expression. You can refer to Print Single Multiple Variable Python for more info about this topic.
In this example, we can see, if we don’t use parentheses in python 2.x then there is no issue but if we don’t use parentheses in python 3.x, we get SyntaxError. 

Python3




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
'''


Unicode In Python

In Python 2, an implicit str type is ASCII. But in Python 3.x implicit str type is Unicode. In this example, difference is shown between both the version of Python with the help of code and also the output in Python comments.

Python3




print(type('default string '))
print(type(b'string with b '))
 
'''
Output in Python 2.x (Bytes is same as str)
<type 'str'>
<type 'str'>
 
Output in Python 3.x (Bytes and str are different)
<class 'str'>
<class 'bytes'>
'''


Python 2.x also supports Unicode 

Python3




print(type('default string '))
print(type(u'string with b '))
'''
Output in Python 2.x (Unicode and str are different)
<type 'str'>
<type 'unicode'>
   
Output in Python 3.x (Unicode and str are same)
<class 'str'>
<class 'str'>
'''


xrange vs range() in both versions

xrange() of Python 2.x doesn’t exist in Python 3.x. In Python 2.x, range returns a list i.e. range(3) returns [0, 1, 2] while xrange returns a xrange object i. e., xrange(3) returns iterator object which works similar to Java iterator and generates number when needed. 
If we need to iterate over the same sequence multiple times, we prefer range() as range provides a static list. xrange() reconstructs the sequence every time. xrange() doesn’t support slices and other list methods. The advantage of xrange() is, it saves memory when the task is to iterate over a large range. 
In Python 3.x, the range function now does what xrange does in Python 2.x, so to keep our code portable, we might want to stick to using a range instead. So Python 3.x’s range function is xrange from Python 2.x. You can refer to this article for more understanding range() vs xrange() in Python.

Python3




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
'''


Error Handling

There is a small change in error handling in both versions. In latest version of Python, ‘as’ keyword is optional. 

Python3




try:
    trying_to_check_error
except NameError, err:
  # Would not work in Python 3.x
    print err, 'Error Caused'  
 
'''
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
'''


In this example, error handling is shown without the use of “as” keyword.

Python3




try:
    trying_to_check_error
except NameError as err:
    print(err, 'Error Caused')
 
# code without using as keyword
try:
    trying_to_check_error
     
# 'as' is optional in Python 3.10
except NameError:
    print('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
'''


__future__ module in Python

This is basically not a difference between the two versions, but a useful thing to mention here. The idea of the __future__ module is to help migrate to Python 3.x. 
If we are planning to have Python 3.x support in our 2.x code, we can use _future_ imports in our code. 
For example, in the Python 2.x code below, we use Python 3.x’s integer division behavior using the __future__ module. 

Python3




# In below python 2.x code, division works
# same as Python 3.x because we use  __future__
from __future__ import division
print(7 / 5)
print(-7 / 5)


Output: 

1.4 
-1.4

Another example where we use brackets in Python 2.x using __future__ module: 

Python3




from __future__ import print_function    
print('GeeksforGeeks')


Output: 

GeeksforGeeks 


Previous Article
Next Article

Similar Reads

Differences Between Pyglet and Pygame in Python
In this article, we will see the difference between Pygame and Pyglet gaming libraries. What is Pyglet? Pyglet is a cross-platform window and media library for Python, intended for developing games and other visually rich applications. It supports windows, UI event handling, gamepads, OpenGL graphics, image and video loading, and sound and music pl
4 min read
Differences between Python Parallel Threads and Processes
In Python, parallelism is a powerful concept used to execute multiple tasks concurrently by improving performance and efficiency. The Two common approaches to parallelism in Python are parallel threads and parallel processes. While both achieve concurrent execution they have distinct characteristics and are suitable for the different use cases. Dif
3 min read
Differences between Flatten() and Ravel() Numpy Functions
We have two similar kinds of ways to convert a ndarray to a 1D array of Flatten() and Ravel() Numpy function in Python programming language. Example of Flatten() Numpy function Here, we will create a Numpy array, and then by using flatten function we have changed the element in the flattened 1D NumPy array. C/C++ Code import numpy as np # Create a
3 min read
Differences between node.js and Tornado
Node.js and Tornado are both popular choices for building scalable and high-performance web applications and services. However, they are based on different programming languages (JavaScript and Python, respectively) and have distinct design philosophies and features. In this guide, we will explore the key differences between Node.js and Tornado, ex
6 min read
Python Program to get all possible differences between set elements
Given a set, the task is to write a Python program to get all possible differences between its elements. Input : test_set = {1, 5, 2, 7, 3, 4, 10, 14} Output : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Explanation : All possible differences are computed. Input : test_set = {1, 5, 2, 7} Output : {1, 2, 3, 4, 5, 6} Explanation : All possible differ
4 min read
Differences between distribute, distutils, setuptools in Python
Overall, distutils is the original package management system for Python, and it is included in the standard library. setuptools is a third-party package that builds on top of distutils and provides additional features and functionality. distribute was a fork of setuptools that has since been merged back into setuptools, and distutils2 was a fork of
6 min read
Differences Between Python vs Matlab
The world is getting to be more logical and measurements situated. That’s the reason logical computing situations are getting more prevalent over the past decade. These situations give more adaptability to researchers and engineers. Like no other programming languages within the world. These languages are offering powerful toolbox together with the
3 min read
Differences Between Django vs Flask
Django and Flask are two of the most popular web frameworks for Python. Flask showed up as an alternative to Django, as designers needed to have more flexibility that would permit them to decide how they want to implement things, while on the other hand, Django does not permit the alteration of their modules to such a degree. Flask is truly so stra
8 min read
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python provides us with a number of in-built data structures such as lists, tuples, sets, and dictionaries that are used to store and organize the data in an efficient manner. In this article, we will learn the difference between them and their applications. Python ListPython Lists are just like dynamic-sized arrays, declared in other languages (ve
4 min read
Compare Keys In Two Yaml Files And Print Differences?
YAML (YAML Ain't Markup Language) files are widely used for configuring applications and storing data in a human-readable format. When dealing with multiple YAML files, it's common to compare them to identify differences, especially when managing configurations across different environments or versions. In this article, we'll explore generally see
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg