Some of us still uses the final version 2.7 of Python 2 which was released in 2010, as Python2 will not be maintained after 2020, so it is a great time to switch to Python3 and accept it with the new changes.
Here I have listed the few changes which I came to know when I started using Python3.
1. Print Function
It was the first change which I came to know, that now the use of parenthesis is must for print as its now treated as function than a statement.
Python2 >>> print “hello world”
Python3 >>>print (“hello world”)
2. Raw_input deprecated
Python2 have two methods to read input from keyboard input and raw_input
In Python3 we only have input( ) and everything is treated as string.
Python2 >>> x = raw_input “hello”
Python3 >>> x = input(“hello”)
3. Integer Division
In Python2 result was rounded to nearest integer for 5/2 and getting a floating result have to give float type integer as 5.0/2.0
In Python3 5/2 result by default it result in float type if result is of float type.
Python2 >>> 5/2 = 2
>>>5.0/2.0 = 2.5
Python3 >>> 5/2 = 2.5
4. Unicode String
In Python2 we need to type u if we want to store a string as Unicode.
print type(unicode("this is a unicode type")
<type "unicode">
print type(b"this is sting")
<type "str">
print type(unicode("this is a unicode type")
<type "unicode">
print type(b"this is sting")
<type "str">
In Python3 it is stored as Unicode by default.
All the strings are now Unicode by default and you have to mark byte sequence with b.
All the strings are now Unicode by default and you have to mark byte sequence with b.
5. range( ) and xrange( )
In Python2 there were two functions range( ) and xrange( ).
Range retuen a list of integers and xrange return xrange object.
Range retuen a list of integers and xrange return xrange object.
In Python3 only range( ) is there.
xrange( ) replaced with range( ).
xrange( ) replaced with range( ).
6. Handling exceptions
In Python2 argument to exception can be declared without using keyword “as”.
In Python2 argument to exception declaration needs “as” keyword.
Python2 >>> except TypeError, err
Python3 >>> except TypeError as err
and there are more changes, but these were the major one I think which I have noticed till now while coding, so will go through the rest also, once I will use them in my code.
No comments:
Post a Comment