When you hear Python 2.x, it means Python 2.7, and Python 3.x, means Python 3.7 version.
The Python 3 version of the Python programming language was released in 2008. Although, there was an initial hesitation around the adoption of the new version.
Literarily most of the libraries/modules of python have been moved to python 3 or have been made compatible to work with it. As such, there is no need to make use of Python 2.x, except if you are working on a legacy code in your application that needs to be run on Python 2.x
Just as said earlier, there are a few changes to Python 3 from Python 2. In the next session we will discuss the most important ones which could cause issues if you are importing your code from Python 2.7 or other 2.x versions to Python 3.x version.
This is one of the noticeable changes, as the print statement is used frequently while coding in Python.
In the old version of python, that is version 2.x, a parenthesis was not added after the print keyword to enclose the text to be printed. However, in version 3.x, the correct syntax is print("TEXT TO BE PRINTED").
Let's see a code example to understand:
# In python 2.x
print "Text to be printed"
Now, when used in Python 3.x, we will have this:
# In python 3.x
print("Text to be printed")
In Python 2.x, the division operator returns an integer result value, while version 3.x returns a more precise float value. Check out the example below:
# In python 2.x
print 5/2
Now, with Python 3.x, we will have something like this.
# In python 3.x
print(5/2)
In the case, of Python 2.x, if you want to generate a list of numbers within a range, the range function, which returns a list; e.g. range(2) will return the list [0,1]. You can also, use the xrange() function as it does not return a list but an iterator object on which you can iterate and obtain the range of numbers. In other words, the xrange() function generates the numbers of range when it is needed only, that is when a loop is used.
For Python 3.x, there is nothing like xrange() function, because the range() function does what xrange() do.
For error handling, there are a few changes in the syntax. Just like the usage of try and except blocks in Python for error handling.
Check out this example below:
# In python 2.x
try:
# some statement that may cause error
except SomeError, err:
print err, "Error Occured"
Now, with Python 3.x, in the except block, the as keyword is used with the error type and its variable object. Check out the example below:
# In python 3.x
try:
# some statement that may cause error
except SomeError as err:
print(err, "Error Occured")
The changes in version 3.x make the syntax more readable and user-friendly. You will learn about Error and Exception handling in subsequent tutorials in this series.
Let’s take a look at some other changes made from version 2.x to 3.x.
Conclusively, you are advised to use Python 3.x version for learning purposes.