Difference between Python 2 and Python 3

Python 2 and Python 3 are two major versions of the Python programming language, each with distinct features and compatibility. Here are some key differences between them:

Print Statement vs. Print Function

In Python 2, printing was accomplished using the print statement, like print "Hello, World!". In Python 3, printing is achieved through the print() function, like print("Hello, World!").

Division Operator

In Python 2, division of integers using the / operator resulted in integer division, truncating the result. In Python 3, division using / between integers performs true division, producing a floating-point result.

Unicode

Python 3 treats all strings as Unicode by default, while in Python 2, strings were a sequence of bytes by default. This difference affects handling of non-ASCII characters and string manipulation.

xrange() vs. range()

In Python 2, the xrange() function was used to generate iterators for ranges, which was memory-efficient. Python 3 eliminates xrange() and uses range() to provide the same behavior.

Input Function

The input() function in Python 3 reads input as a string, whereas in Python 2, it evaluated the input as a Python expression.

Exception Handling

Python 3 introduced a more consistent syntax for exception handling, requiring parentheses around exception instances. Python 2 used a comma-separated format.

Iterable Methods

Python 3 introduced iterable methods like items(), keys(), and values() for dictionaries, while Python 2 used methods like iteritems(), iterkeys(), and itervalues().

Print in Loops

In Python 2, the print statement within a loop automatically added a newline, while in Python 3, the print function does not add a newline by default.

Example of a Python 2 code snippet:
# Python 2 print "Hello, World!"
Equivalent Python 3 code:
# Python 3 print("Hello, World!")

Conclusion

Python 2 and Python 3 exhibit distinctions in syntax, features, and behavior. Python 3 introduces improvements like Unicode string handling, print function, and division operator behavior, necessitating code adaptation for compatibility between the two versions.