7 Major Differences Between Python 2.X & Python 3.X

Python Programming Language is one of the most popular programming languages in the world. Python took a major leap when it launched its version 3.x in year 2008. There are significant performance increases along with other enhancements. At present, the latest stable version of Python is 3.10. Let’s now see some of the major differences:-

Print(): One of the prominent changes which has happened in python 3 is a change in the print method. In python 3, the print keyword in Python 2.x is replaced by the print() function. Note: parentheses work in Python 2 if space is added after the print keyword because then the interpreter evaluates it as an expression.

Division: In python 2.x, when 2 integers are divided the result is always an integer. Whereas, in python 3.x when 2 integers are divided the result is a float value.

Xrange: In pythn 2.x, range() and xrange() functions are available. Range returns list of elements & xrange() returns an iterable object. But in python 3.x, xrange() and range has been merged into one .i.e. range().

Error Handling: In python 3.x, ‘as’ keyword is required in try-except block and this is mandatory. If as is not mentioned, the code will throw an error.

__future__ module: 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.

List Comprehension Loop Variables: In python 2, if loop variables and global variables are of same name, the values of global variables changes after the execution of list comprehension. This problem was solved in python 3.x

Unicode Strings: In python 2, the strings were saved as ASCII but in python 3.x strings are stored by default as unicode. This means that in Python 3.x, you can use characters from any language in your code without having to encode or decode them. In Python 2.x, you can use the u"Hello World" syntax to create Unicode strings, while in Python 3.x, you can simply use "Hello World". The u prefix is not necessary in Python 3.x.

Python 3.x is now used everywhere and python 2.x is very outdated, its always better to know some of the major differences.

The codes (if any) mentioned in this post can be downloaded from github.com. Share the post with someone you think can benefit from the information

Share this