Posted on

The key differences between Python 2.x and Python 3.x with examples

Free-clip-art-thinkingMany novice Python users are wondering with which version of Python they should start. My answer to this question is usually something along the lines “just go with the version your favourite tutorial was written in, and check out the differences later on.”

But what if you are starting a new project and have the choice to pick? I would say there is currently no “right” or “wrong” as long as both Python 2.7.x and Python 3.x support the libraries that you are planning to use. However, it is worthwhile to have a look at the major differences between those two most popular versions of Python to avoid common pitfalls when writing the code for either one of them, or if you are planning to port your project. After looking at the differences if you are still not able to decide then this post might help.

What are the differences?

Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is under active development and has already seen over five years of stable releases, including version 3.3 in 2012, 3.4 in 2014, 3.5 in 2015, and 3.6 in 2016. This means that all recent standard library improvements, for example, are only available by default in Python 3.x.

Guido van Rossum (the original creator of the Python language) decided to clean up Python 2.x properly, with less regard for backwards compatibility than in the case for new releases in the 2.x range. The most drastic improvement is the better Unicode support (with all text strings being Unicode by default) as well as saner bytes/Unicode separation.

Besides, several aspects of the core language (such as print and exec being statements, integers using floor division) have been adjusted to be easier for newcomers to learn and to be more consistent with the rest of the language, and old cruft has been removed (for example, all classes are now new-style, “range()” returns a memory efficient iterable, not a list as in 2.x).

The What’s New in Python 3.0 document provides a good overview of the major language changes and likely sources of incompatibility with existing Python 2.x code. Nick Coghlan (one of the CPython core developers) has also created a relatively extensive FAQ regarding the transition.

However, the broader Python ecosystem has amassed a significant amount of quality software over the years. The downside of breaking backwards compatibility in 3.x is that some of that software (especially in-house software in companies) still doesn’t work on 3.x yet.

Some syntax differences :-

Division operator

If we are porting our code or executing the python 3.x code in python 2.x, it can be dangerous if integer division changes go unnoticed (since it doesn’t raise any error). It is preferred to use the floating value (like 7.0/5 or 7/5.0) to get the expected result when porting our code.

print 7 / 5
print -7 / 5   
 
'''
Output in Python 2.x
1
-2
Output in Python 3.x :
1.4
-1.4
 
'''

print function
This is the most well known change. In this the print function in Python 2.x is replaced by print() function in Python 3.x,i.e, to print in Python 3.x an extra pair of parenthesis is required.

print 'Hello, Geeks'      # Python 3.x doesn't support
print('Hope You like these facts')
 
'''
Output in Python 2.x :
Hello, Geeks
Hope You like these facts
 
Output in Python 3.x :
File "a.py", line 1
    print 'Hello, Geeks'
                       ^
SyntaxError: invalid syntax
 
'''

As we can see, if we use parenthesis in python 2.x then there is no issue but if we don’t use parenthesis in python 3.x, we get SyntaxError.

Unicode
In Python 2, implicit str type is ASCII. But in Python 3.x implicit str type is Unicode.

print(type('default string '))
print(type(b'string with b '))
 
'''
Output in Python 2.x (Bytes is same as str)
<type 'str'>
<type 'str'>
 
Output in Python 3.x (Bytes and str are different)
<class 'str'>
<class 'bytes'>
'''

Python 2.x also supports Unicode

print(type('default string '))
print(type(u'string with b '))
 
'''
Output in Python 2.x (Unicode and str are different)
<type 'str'>
<type 'unicode'>
 
Output in Python 3.x (Unicode and str are same)
<class 'str'>
<class 'str'>
'''

xrange
xrange() of Python 2.x doesn’t exist in Python 3.x. In Python 2.x, range returns a list i.e. range(3) returns [0, 1, 2] while xrange returns a xrange object i. e., xrange(3) returns iterator object which work similar to Java iterator and generates number when needed.
If we need to iterate over the same sequence multiple times, we prefer range() as range provides a static list. xrange() reconstructs the sequence every time. xrange() doesn’t support slices and other list methods. The advantage of xrange() is, it saves memory when 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 might want to stick to using range instead. So Python 3.x’s range function is xrange from Python 2.x.

for x in xrange(1, 5):
    print(x),
 
for x in range(1, 5):
    print(x),
 
'''
Output in Python 2.x
1 2 3 4 1 2 3 4
 
Output in Python 3.x
NameError: name 'xrange' is not defined
'''

Error Handling

try:
    trying_to_check_error
except NameError, err:
    print err, 'Error Caused'   # Would not work in Python 3.x
 
'''
Output in Python 2.x:
name 'trying_to_check_error' is not defined Error Caused
 
Output in Python 3.x :
File "a.py", line 3
    except NameError, err:
                    ^
SyntaxError: invalid syntax
'''
try:
     trying_to_check_error
except NameError as err: # 'as' is needed in Python 3.x
     print (err, 'Error Caused')
 
'''
Output in Python 2.x:
(NameError("name 'trying_to_check_error' is not defined",), 'Error Caused')
 
Output in Python 3.x :
name 'trying_to_check_error' is not defined Error Caused
'''

_future_module
This is basically not a difference between two version, but useful thing to mention here. The idea of __future__ module is to help in migration. We can use Python 3.x
If we are planning Python 3.x support in our 2.x code,we can ise_future_ imports it in our code.

For example, in below Python 2.x code, we use Python 3.x’s integer division behavior using __future__ module

# In below python 2.x code, division works
# same as Python 3.x because we use  __future__
from __future__ import division
 
print 7 / 5
print -7 / 5
''' output
1.4
-1.4
'''

 
 

 

Posted on

Should I use Python 2 or Python 3 for my development activity?

thinker-28741_640Python is without any doubt one of the most talked about programming language in this Universe. It’s everywhere, and because of how simple it is to learn it – many beginners start their career with Python. The syntax of Python is very similar to that of English language, with the exception of a few extra characters here and there. Currently there are two main versions of Python, Python 2 and Python 3, that have slight differences in their syntax and their support of different libraries. You can refer this post to know the key differences between Python 2 and Python 3.

No doubt both versions of Python are good but many a times, beginners get confused while choosing one of the two for their development purpose. In this article I will try to explain which Python version can you use to start your development.

What are the differences?

Short version: Python 2.x is legacy, Python 3.x is the present and future of the language

In order to avoid making this post too long, I will be avoiding the details of differences between the two versions. The detailed post on differences between Python 2 and Python 3 can be found here.

Which version should I use?

Which version you ought to use is mostly dependent on what you want to accomplish.

If you can do exactly what you want with Python 3.x, great! There are a few minor downsides, such as very slightly bad library support and the fact that some current Linux distributions and Macs are still using 2.x as default (although Python 3 ships with many of them), but as a language Python 3.x is definitely ready. As long as Python 3.x is installed on your user’s computers (which ought to be easy, since many people reading this may only be developing something for themselves or an environment they control) and you’re writing things where you know none of the Python 2.x modules are needed, it is an excellent choice. Also, most Linux distributions have Python 3.x already installed, and available for end-users. Some are phasing out Python 2 as pre-installed default.

In particular, instructors introducing Python to new programmers should consider teaching Python 3 first and then introducing the differences in Python 2 afterwards (if necessary), since Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers trying to learn Python 2.

However, there are some key issues that may require you to use Python 2 rather than Python 3.

  • Firstly, if you’re deploying to an environment you don’t control, that may impose a specific version, rather than allowing you a free selection from the available versions.
  • Secondly, if you want to use a specific third party package or utility that doesn’t have a released version that is compatible with Python 3, and porting that package is a non-trivial task, you may choose to use Python 2 in order to retain access to that package.

Python 3 already broadly supports creating GUI applications, with Tkinter in the standard library. Python 3 has been supported by PyQt almost from the day Python 3 was released; PySide added Python 3 support in 2011. GTK+ GUIs can be created with PyGObject which supports Python 3 and is the successor to PyGtk.
Many other major packages have been ported to Python 3 including:

  • NumPy and SciPy (for number crunching and scientific computing)
  • Django, Flask, CherryPy and Pyramid (for Web sites)
  • NumPy and SciPy (for number crunching and scientific computing)
  • Django, Flask, CherryPy and Pyramid (for Web sites)
  • And many, many more!

If you want to use Python 3.x, but you’re afraid to because of a dependency, it’s probably worthwhile doing some research first. This is a work in progress. Furthermore, with the large common subset supported by both Python 2.6+ and Python 3.3+, many modern Python code should run largely unmodified on Python 3, especially code written to interoperate with web and GUI frameworks that force applications to correctly distinguish binary data and text (some assistance from the six compatibility module may be needed to handle name changes).

Even though the official python documentation and the tutorial have been completely updated for Python 3, there is still a lot of documentation (including examples) on the Web and in reference books that use Python 2, although more are being updated all the time. This can require some adjustment to make things work with Python 3 instead.

Some people just don’t want to use Python 3.x, which is their prerogative. However, they are in the minority.
It is worth noting that if you wish to use an alternative implementation of Python such as IronPython, Jython or Pyston (or one of the longer list of Python platform or compiler implementations), Python 3 support is still relatively rare. This may affect you if you are interested in choosing such an implementation for reasons of integration with other systems or for performance.

Thumbs Up

 

 

Posted on

10 python modules you must know about

Python_logoWithout any doubt Python is one of the most talked about programming language in this Universe. It’s everywhere, and because of how simple it is to learn it – many beginners start their career with Python. The syntax of Python is very similar to that of English language, with the exception of a few extra characters here and there. In this post you will know about 10 important python modules you should know.

 

1. NumPy

 

NumPy provides some advance math functionalities to python. This package is mainly designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays. There are also basic facilities for discrete fourier transform, basic linear algebra and random number generation.

 

2. SciPy

 

SciPy is a library of algorithms and mathematical tools for python and has caused many scientists to switch from ruby to python. It is mainly used for scientific computing and technical computing. SciPy contains modules for optimization, linear algebra, integration, interpolation, special functions, signal and image processing, ODE solvers and other tasks common in science and engineering.

 

3. Pandas

 

Pandas is a Python package designed to do work with “labeled” and “relational” data simple and intuitive. Pandas is a perfect tool for data wrangling. It designed for quick and easy data manipulation, aggregation, and visualization.

 

4. matplotlib

 

matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It is a library mainly used for making 2D plots of arrays in Python. It is very useful for any data scientist or any data analyzer.

 

5. IPython

 

IPython is a command shell for interactive computing in Python and other programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history.

 

6. PyGame

 

This is a interesting python module for developers who like to play games and develop them.This library will help you achieve your goal of 2d game development.

 

7. Twisted

 

Twisted is an event-driven networking engine written in Python and licensed under the open source MIT license.It is the most important tool for any network application developer. It has a very beautiful api and is used by a lot of famous python developers.

 

8. PrettyTable

 

As the name already suggests, prettytable is a table printing library which displays the contents of the table as a pretty formatted table on the console.

 

9. nose

 

nose is a testing framework for Python. Their tagline is: “nose extends unit test to make testing easier.” It is used by millions of python developers. It is a must have if you do test driven development.

 

10. Scrapy

 

Scrapy is a free and open source web crawling framework, written in Python. Originally designed for web scraping, it can also be used to extract data using APIs or as a general purpose web crawler.

 

 

Posted on

5 Top Python Frameworks For Web Developers

A Web framework can be very helpful for developers to write Web applications without having to handle low-level details as protocols, sockets or process/thread management. But a perfect choice might depend on a developer specific needs, preferences, and skill level. Python is a dynamic, object-oriented language. It was originally designed as an object-oriented language and some more advanced features were added in the later versions. In addition to the design purpose of language itself, the Python standard library is worth praising, and it even brings its own server. In other aspects, Python has enough free data library, free Web page template system and the library interacting with the Web server, which can be designed to your Web application. In this article we are going to look at 5 top Python Frameworks(according to me) for web development purpose.
1. Django

Screenshot from 2017-06-26 17-15-46
Django is a high-level Python Web framework that encourages fast growth and clean, pragmatic design. In case you are building something that’s much like a e-commerce web site, then it’s best to, in all probability, go along with Django. It would get your work executed fast. You do not have to fret about too many expertise selections. It gives the whole lot factor you want from template engine to ORM. If you wish to use your web app framework as a CMS, Django might be a more sensible choice. It’s free and open source.

2. Flask
Screenshot from 2017-06-26 17-22-07
Flask Python framework is highly extensible. A newbie programmer may find Flask inefficient due to lack of features like form validation, and database abstraction layer. In such a case, know that Flask allows you to implement extensions; therefore, you can add any required functionality.

3. CherryPy
Screenshot from 2017-06-26 17-28-40
CherryPy is a Web application development framework based on Python, that greatly simplifies the work of Python Web developers. It provides a friendly HTTP protocol interfaces for Python developers. CherryPy has a built in HTTP server or Web server, so the users of CherryPy can directly run CherryPy application without building Web server.

4. Pyramid
Screenshot from 2017-06-26 17-30-23
Pyramid is an open source, Python web application development framework. Its primary goal is to make it easier for a Python developer to create web applications. Pyramid is similar to Flask . Pyramid is compatible with python3, with a great documentation, its minimal, fast and flexible and has an integration of nosql: mongodb, couchdb . Pyramid is best for Developers working on API projects, prototyping a concept & developing large web applications, such as a CMS.

5. Web2py
Screenshot from 2017-06-26 20-13-12
Web2py is a free open source full-stack framework for rapid development of fast, scalable, secure and portable database-driven web-based applications. Written and programmable in Python.

 

 

Posted on

5 Best IDE for Python Programmers

An integrated development environment (IDE) is a software suite that consolidates the basic tools developers need to write and test software. Typically, an IDE contains a code editor, a compiler or interpreter and a debugger that the developer accesses through a single graphical user interface (GUI). An IDE may be a standalone application, or it may be included as part of one or more existing and compatible applications. In this article we will know about the 5 best IDE (according to me) for Python Developers

1. VIM

VIM is one of the most advanced text editors and is very popular one among the community of Python developers. It is open source and available free of cost under GPL license. Vim though is best known as an editor but it offers nothing less than a full featured Python development environment when configured correctly for Python development. VIM is light weight, modular and fast and is best suited for programmers who love keyboards and only keyboards, no mouse use while coding.

 


2. Sublime Text 3 / Anaconda Python IDE

Sublime Text 3 is one of the most powerful cross platform lightweight code editors till date. With the use of plugins Sublime Text 3 can be used as a full featured IDE – the Sublime Python IDE. You get elegance of sublime text and powers of Python at one place to create your own magic. The most powerful transformation is brought to you by Anaconda package which provides code completion and linting for Python.

3. Pydev with Eclipse – Best Python IDE (Free Tier)

Pydev is the Python IDE for masses for the simple reason that it is free of cost and comes packed with powerful features for efficient Python programming. It is an open source plugin that runs on top of Eclipse and brings Python to the kingdom of Eclipse. If you are an existing Eclipse user then Pydev is just home for you, if not, then Eclipse might sound intimidating in the beginning but worth the efforts.

4. Emacs – Python Editor cum IDE

Emacs has an ecosystem of its own. It is the GNU text editor which is extensible and highly customizable. When it comes to Python programming, Emacs can be configured in such a way that it gets transformed into a fully functional free Python IDE.

5. Spyder Python

Spyder Python is an open source IDE for Python, best suited for scientific python development. It is a lightweight software, written in Python itself and available as free to use under MIT license. Some of the basic features of Spyder python are multi language editor, interactive console, documentation viewer, variable explorer, Find in files, files explorer etc. It can get Spyder IDE package for windows, Mac or Linux.