Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Download and Install Python 3 Latest Version
Next article icon

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

Last Updated : 06 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
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:

  • Division operator
  • print function
  • Unicode
  • xrange
  • Error Handling
  • _future_ module

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  

Next Article
Download and Install Python 3 Latest Version

K

kartik
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    How to Learn Python from Scratch in 2025
    Python is a general-purpose high-level programming language and is widely used among the developers’ community. Python was mainly developed with an emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.If you are new to programming and want to lea
    15+ min read
    Python Introduction
    Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPython’s simple and readable syntax makes it beginner-frien
    3 min read
    Python 3 basics
    Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the
    10 min read
    Important differences between Python 2.x and Python 3.x with examples
    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: Division operatorprint functionUnicodexrangeError Handling
    5 min read
    Download and Install Python 3 Latest Version
    If you have started learning of Python programming, then for practice, Python installation is mandatory, and if you are looking for a guide that teaches you the whole process from downloading Python to installing it, then you are on the right path.Here in this download and install Python guide, we h
    6 min read
    Statement, Indentation and Comment in Python
    Here, we will discuss Statements in Python, Indentation in Python, and Comments in Python. We will also discuss different rules and examples for Python Statement, Python Indentation, Python Comment, and the Difference Between 'Docstrings' and 'Multi-line Comments. What is Statement in Python A Pytho
    7 min read
    Python | Set 2 (Variables, Expressions, Conditions and Functions)
    Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on th
    3 min read
    Global and Local Variables in Python
    In Python, global variables are declared outside any function and can be accessed anywhere in the program, including inside functions. On the other hand, local variables are created within a function and are only accessible during that function’s execution. This means local variables exist only insi
    7 min read
    Type Conversion in Python
    Python defines type conversion functions to directly convert one data type to another which is useful in day-to-day and competitive programming. This article is aimed at providing information about certain conversion functions. There are two types of Type Conversion in Python: Python Implicit Type C
    5 min read
    Private Variables in Python
    Prerequisite: Underscore in PythonIn Python, there is no existence of “Private” instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences