Important differences between Python 2.x and Python 3.x with examples
Last Updated :
20 Sep, 2025
In this article, we will explore some important differences between Python 2.x and Python 3.x with the help of examples, focusing on the following libraries and modules.
- Division operator
- print function
- Unicode
- xrange
- Error Handling
- _future_ module
1. Python Division operator
- In Python 2.x: dividing two integers performs floor division (discards decimals).
- In Python 3.x: dividing two integers performs true division (keeps decimals).
Python
print 7 / 5
print -7 / 5
print(7 / 5)
print(-7 / 5)
Output in 2.x:
1
-2
Output in 3.x:
1.4
-1.4
2. Print Function in Python
- In Python 2.x: print is a statement (no brackets needed).
- In Python 3.x: print is a function, so parentheses are required.
Python
# Python 2.x
print 'Hello, Geeks' # print is a statement
print('This works too') # works because it's treated like a function call
# Python 3.x
print('Hello, Geeks') # print is a function (this is the only correct way)
Output in Python 2.x:
Hello, Geeks
This works too
Output in Python 3.x:
Hello, Geeks
3. Unicode In Python
- Python 2.x: Strings are ASCII by default, unicode must be defined separately.
- Python 3.x: Strings are Unicode by default.
Python
print(type('default string'))
print(type(b'string with b'))
Output in Python 2.x:
<type 'str'>
<type 'str'>
Output in Python 3.x:
<class 'str'>
<class 'bytes'>
4. xrange() vs range()
Python 2.x:
- range() returns a list.
- xrange() returns a generator (saves memory).
Python 3.x:
- xrange() is removed.
- range() behaves like Python 2’s xrange.
Python
# Python 2.x
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
- Python 2.x: Uses a comma to bind the exception.
- Python 3.x: Uses as keyword (comma syntax no longer works).
Python
# Python 2.x
try:
x = not_defined
except NameError, err:
print err, 'Error Caused'
Output in Python 2.x:
name 'not_defined' is not defined Error Caused
Output in Python 3.x:
SyntaxError: invalid syntax
Correct way (works in both):
try:
x = not_defined
except NameError as err:
print(err, 'Error Caused')
6. __future__ module in Python
__future__ module allows Python 2 code to adopt Python 3 features early, making migration easier.
Example 1: Division behavior
Python
from __future__ import division
print(7 / 5)
print(-7 / 5)
Output (Python 2.x with future import):
1.4
-1.4
Output (Python 3.x):
1.4
-1.4
Example 2: print as a function
Python
from __future__ import print_function
print('GeeksforGeeks')
Output (Python 2.x with future import):
GeeksforGeeks
Output (Python 3.x with future import):
GeeksforGeeks
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice