Key Differences Between Python 2.7.x and Python 3.x



Python 3.0 was released in December 2008. It was designed to rectify certain flaws in earlier versions. Python 3.0 doesn't provide backward compatibility. That means a Python program written using version 2.x syntax doesn't execute under the Python 3.x interpreter. Version 2.7 is the final major release in the Python 2.x series.

The guiding principle of Python 3 was: "reduce feature duplication by removing old ways of doing things".

Although there are quite a few differences in usage of these two versions, the most obvious ones are mentioned below -

Print Statement Vs Function

print is a keyword in Python 2.7 but has been included as a built-in function in Python 3.x. As a result, parentheses are mandatory when using them in Python 3 code -

#print "Hello World"
# is acceptable in Python 2 but not in Python 3
print ("Hello World") 
#acceptable in Python 2 and Python 3

Following is the output of the above program -

Hello World

Input Functions

Python 2 has a separate function for string and a different one to evaluate input, while Python 3 has a single function that returns strings. The raw_input() function from Python 2.7 has been deprecated. The input() function treats the received data as a string only.

# Python 2
user_input = raw_input("Enter text: ")  # Returns string
evaluated = input("Enter expression: ")  # Evaluates as Python code!

# Python 3
user_input = input("Enter text: ")      # Always returns string

Integer Division

The functionality has been changed in Python 3. In Python 2.x, 5/2 results in 2, but in Python 3.x, 5/2 is 2.5.

# Python 2
user_input = raw_input("Enter text: ")  # Returns string
evaluated = input("Enter expression: ")  # Evaluates as Python code!

# Python 3
user_input = input("Enter text: ")      # Always returns string

String Handling

In Python 3.x, a string is Unicode by default. In Python 2.x, the string has to be explicitly defined as Unicode by prefixing it with ?u' ( e.g., u'hello').

# Python 2
regular = "Hello"        # ASCII or bytes
unicode = u"Hello"       # Unicode string

# Python 3
text = "Hello"           # All strings are Unicode by default
binary = b"Hello"        # Bytes for binary data

Long Integers

In Python 3.x, integer objects are long by default. In Python 2.x, an integer has to be postfixed by L (e.g. 100L).

# Python 2
x = 1000000000000L       # Long integer with 'L' suffix

# Python 3
x = 1000000000000        # All integers are "long" by default

Exception Handling

The syntax for catching exceptions was improved in Python 3 to use the as keyword instead of a comma.

# Python 2
try:
    # code
except Exception, e:
    # handle error

# Python 3
try:
    # code
except Exception as e:
    # handle error
Updated on: 2025-05-02T21:40:20+05:30

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements