Difference between python 2 and 3

python 2 vs python 3

Till the recent past, there was a bit of debate among Pythonistas to decide among python 2 and 3 in terms of Writing code (fast prototyping), application, Run-time execution, rich library support, better third-party integration, and experienced community support. At present, in 2020, there is no confusion about which python version to use (undoubtedly it’s Python 3). There are still many programmers out there who continue using python 2.x as those projects were built and grown in python 2.

This is clear advice to the reader that either if you want to get started with python from basic or willing to sharpen your python skillset then always go ahead with python 3. In this article, we will be addressing multiple factors which makes Python 3 a clear winner over python 2 and why the major technology giants are leaping to python 3. Read this article and if you like the content then do help others by sharing it. It is extremely easy to learn python.


Table of contents

  1. Background of Python
    1. Global trends of python 2 and 3
  2. What made Python 3 popular
  3. Python 2 vs Python 3 video
  4. The key difference between python 2 and 3
    1. User Input
    2. Print function
    3. NOT equal operator
    4. __future__ modules
    5. Integer Division
    6. Unicode
    7. Iteration range function
    8. Error Handling
      1. Raising exceptions
      2. Handling exceptions
  5. Why organization are choosing python 3 over 2
  6. Why should you use Python 3
  7. Conclusion

Background of python

The first version of Python 2, which is Python 2.0, was released in the year 2000 and since then it was being used by millions of programmer. Python 2 had developed over the years with rigorous modifications, updates, bug-fixes and eventually grew matured. There were dozens of library added and updated in python version 2, which still exists. Latest and the last version of python 2 is python 2.7. It is still a legacy python version and there exists a lot of projects based on it.

However, PSF (Python software foundation) being responsible for managing, modifying and providing sets of guidelines for new implementation in python, declared Sunsetting of python 2. Starting 1st January 2020 no new bug reports, fixes, or changes will be made to Python 2 and it will no longer be supported by PSF. Nearly all popular libraries have already ported their code, Python 2.x is well on its way to antiquation.

Have a look at the amazing journey cum timeline of Python shown in the image below.

python timeline aipython

Python 3 was born in the year 2008 as a successor of Python 2 with more user-friendliness, flowless design and fast. Fundamentally, Python 3 is different from its previous version as this was the first time when the python was not back-compatible. Yes, the code written in python 2 can not be used or executed in python 3 and vice-versa. However, Python 3 code can be handled within python 2 in a bit easier way using __future__ module.

We will discuss this module in the later section of this article. Since 2008, Python 3 had grabbed a lot of attention from a myriad of developers, hobbyist, enthusiast, students and many more. More modern and advanced libraries are available exclusively for python 3. As of 2020, after 12 years, Python 3 undoubtedly has become the ultimate choice for programming and clearly is the future.

The image below (source: Google Trends) shows the global trends for Python 2 and 3 and from the image is crystal clear that more and more people are opting for Python 3 as well as industries are inclining towards it.

google trends for python 2 and python 3

Python 3 is the future. Now, you wanted to know why Python 3 is given priority over Python 2 as well what are the reasons for its popularity and growing demands. Here are the facts,

  • Python 3 provides libraries for AI, Machine Learning, Deep Learning, Natural Language Processing and Data Science which are currently the world’s most in-demand technology. Most of the development and research in these areas are happening using the new python version. It is growing immensely.
  • A huge developers community and user base are helping out the fast and reliable development of Python 3. So getting support is easy in this case.
  • Python 3 supports modern libraries for almost all spectrums of application. One more reason for people to choose python 3 as the option to work in a variety of domains using the same language.
  • The programmer uses Python 3 to invoke another program as well as exchange the data with various external software.
  • It is comparatively easier to learn compared to the previous version of Python.
  • Large base of technology giants is working and looking for professionals well versed with Python 3. Some admirable brand like Google, Facebook, Instagram, Dropbox, Netflix and many others are working on Python 3.

Watch the video for Python 2 vs Python 3


The key difference between python 2 and 3

Programming language constantly evolves as developers extend the functionality as well as improve the programmability. The newer version of the language is less confusing for a new user to learn. Find out the major differences between python 2 and 3.

User Input

In Python, expressions are anything meaningful that a programmer writes to complete the code may it be a string declaration, variable initialization or instance of a class. Python 2 and 3 show variation in their syntax for receiving user inputs. Python 2 uses raw_input for receiving user’s input while its successor uses input only.

 X = raw_input("Please enter a value") 
X = input("Please enter a value") 

The print function is perhaps the most commonly used in python. In Python 2, the print was merely a keyword and not the function. The print statement was modified to print () function in Python 3.

print  'Welcome to aipython'
Welcome to aipython 
print ('Welcome to aipython')
Welcome to aipython 

NOT Equal Operator:

In Python 2, the NOT EQUAL operator symbol used to be <>, whereas, in Python 3 it had been replaced with !=. Functionality remains the same in both cases.

7 <> 6
True 
7 != 6
True 

__future__ module

This is read as “double underscore future double underscore” module. Python 2 uses __future__ module (don’t confuse by its name) to import new features (port to python) from Python 3. It is recommended to use __future__ imports it if you are planning Python 3.x support for your code. For example, if we want to use Python 3’s integer division behaviour in Python 2, we can import it using __future__ module.

from __future__ import division

Similarly, there are various other functions which we can be imported using the __future__ module. A detailed list of functions are provided on the Python website and the same is mentioned below.

from __future__ import nested_scopes
from __future__ import generators
from __future__ import absolute_import
from __future__ import with_statement 
from __future__ import print_function 
from __future__ import unicode_literals 

Alternately, you can also import every functionality using a single line, which is

 import __future__

Integer Division

The Integer Division (symbol ‘/’ ) is also considered as on the most significant changes that happened from python2 to python 3. In python2, the result of integer division used to be an integer to the nearest integer value, whereas, in Python 3, the result of integer division is always in the float.

3/2
1 
3/2
1.5  

Unicode

Unicode is the universal character encoding, maintained by the Unicode Consortium. This encoding standard provides the basis for processing, storage and interchange of text data in any language in all modern software and information technology protocols. Unicode strings are more versatile than ASCII strings, which are the Python 2 default, as they can store letters from foreign languages as well as emoji and the standard Roman letters and numerals. Python 3 stores strings as Unicode by default, whereas Python 2 requires you to mark a string with a “u” if you want to store it as Unicode. Python 3 has been equipped with Unicode (UTF-8), byte and bytearray. Type () function can be used to get datatype or the class of an object in python. 

print type('this is not Unicode')
<class 'str'>

print type(u'this is not Unicode')
<class 'unicode'>

print type(b'No byte class in python 2')
<class 'str'> 
print('strings are now utf-8 \u03BCnico\u0394é!')
strings are now utf-8 μnicoΔé!

print(type('strings are now utf-8 \u03BCnico\u0394é!'))
<class 'str'> #String class understand unicode

 print (type(b'This is now byte in Python 3'))
 <class 'bytes'>  

Iteration range function (xrange function)

xrange is used with python 2.x for creating an iterable object, where values can not be extracted, to execute a loop (especially a for-loop). In python 3, xrange () function is replaced by range (). range function returns a list of number starting with 0 up to the length of the parameter whereas xrange function returns an iterable object. xrange() raises a NameError in Python 3. Although both are used for iteration purpose still xrange() doesn’t support slices and other list methods.

 xrange(5)
range(5)
range(0,5) 

x = range(5)
print (x)
[0 ,1 ,2 ,3 ,4]   

Error Handling

Both versions of Python have significant built-in error handling mechanism and this broadly classifies in two categories i.e. Raising exception and Handling exception. Raising exception are used to provide alerts to the user about what went wrong during the execution while exception handling tries to continue the execution without terminating the program.

Raising exception

Raising an exception means forcefully throw an information/error message to the user about the issue. There are pre-defined exceptions available in python though on top of that python provides to create a custom exception. We can use the raise keyword to throw an exception if a certain condition occurs. The statement can be complemented with a custom exception meaning you can write your text to be displayed. You can find the nicely explained article on Python Exception

raise ValueError "This is not a valid value"
Exception: This is not a valid value 
raise ValueError ("This is not a valid value")
Exception: This is not a valid value

Handling Exception

In Python 3, the try and except block are helpful to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

try:
     <content of try block>
except ValueError, Val_error:
    print Val_error, 'write any custom message within this quote'   
try:
     <content of try block>
except ValueError as val_err:
    print(val_err, 'Write any custom message within this quote')  

Why organization are choosing python 3

As mentioned earlier, Python 2 had already sunsetted on Jan 1, 2020, many organizations are already in the process to migrate from Python 2 to 3. Big corporations like Google, Facebook, Instagram, ILM, Netflix, Quora, Dropbox and many more are already using Python 3 and they are looking for professionals with a similar skillset. One of the amazing places to test your preparedness towards being a Python developer (beginner/experienced) is hiring guide. You can apply for Python developer or hire someone.

There are many reasons for the transition and some of them are here below

  1. Python is a dynamically typed language which makes the development process fast.
  2. Python 3 is richer in terms of modern library and modules.
  3. Supports toolbox (or library) for Machine Learning, AI, Deep Learning, Neural Networks etc.., which are the hot trending topic in the technology sphere.
  4. Large and active community supports in getting through all the queries.
  5. Execution in Python 3 is faster as compared to 2.

Why should you use Python 3

By now you would have got the idea why Python 3 is so popular and why it is the future. You should choose Python 3 over Python 2, whether you are a student, professional, technician, developer, Automator or hobbyist.

I would give you five major reason behind choosing Python 3 over 2.

  1. A large support community to help each other.
  2. Understanding this language is easy for a beginner or advanced programmer.
  3. Modern libraries such as AL, ML, DL, CV and many more are available for Python 3. Most of the work in such an area is happening in Python 3.
  4. Organizations are also looking for professionals having experience in Python 3.
  5. More and more career opportunity. 

Conclusion

We have seen a lot of details on the topic and also understood why everyone is migrating to the newer version of Python. As of 2020, Python 3 is the future as well the winner. Improved python 3 syntax, dynamically typed language, Faster execution and large community base are making this transition a success. There is should be no doubt left on why to switch to Python 3.0 (any Python 3.x), however, if you have any doubt on this post or related article then please write us in the comment section. We would love to hear from you and you will get the response for sure.

Keep Learning and Keep Growing !!

How did you like the content