VOOZH about

URL: https://www.geeksforgeeks.org/python/important-differences-between-python-2-x-and-python-3-x-with-examples/

⇱ Important differences between Python 2.x and Python 3.x with examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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).

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.

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.


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.

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).

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

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

Output (Python 2.x with future import):

GeeksforGeeks

Output (Python 3.x with future import):

GeeksforGeeks

Related Articles:

Comment
Article Tags:
Article Tags: