If we are porting our code or executing python 3.x code into python 2.x, it can be dangerous if integer division changes go unnoticed (since this does not cause any error). It is preferable to use a float (like 7.0 / 5 or 7 / 5.0) to get the expected result when we wrap our code.
This is the most famous change. This replaces the print function in Python 2.x with the print () function in Python 3.x, meaning that printing in Python 3.x requires an extra pair of parentheses.
| tr> |
As we can see, if we use parentheses in Python 2.x, then this is not a problem, but if we don’t use parentheses in Python 3.x, we get SyntaxError.
In Python 2, the implicit type str — ASCII. But in Python 3.x the implicit type str is Unicode.
Python 2.x also supports Unicode
xrange () in Python 2.x does not exist in Python 3.x. In Python 2.x, range returns a list, i.e. range (3) returns [0, 1, 2], and xrange returns an xrange object, that is, Xrange (3) returns an iterator object that works like a Java iterator and generates a number as needed.
If we need to repeat the same sequence multiple times, we prefer range () because range provides a static list. xrange () rebuilds the sequence every time. xrange () does not support slices or other list methods. The advantage of xrange () is that 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 could stick with using range instead. So, the range function in Python 3.x — this xrange from Python 2.x.
Both versions there are small changes in error handling. In python 3.x, the "as" keyword is required.
This is basically not the difference between the two versions but it is useful to mention here. The idea of the __future__ module — help in m games. We can use Python 3.x
If we plan to support Python 3.x in our 2.x code, we can use _future_, by importing it into our code.
For example, in the Python 2.x code below, we are using Python 3.x integer division behavior using the __future__ module
Another example where we use parentheses in Python 2.x using the __future__ module
Refer to this for more details on the __future __ module.
This st This article is provided by Arpit Agarwal . If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you’d like to share more information on the topic under discussion