[Getting started with Python from scratch] Important differences and examples between Python 2.x and Python 3.x

✍For readers: everyone

✍Column : Python zero-based introductory tutorial

Differences between Python 2.x and Python 3.x

Python division operator

Print function in Python

Unicode in Python

xrange and range() in two versions

Error handling

__future__ module in Python

In this article, we will understand some important differences between Python 2.x and Python 3.x with some examples.

Differences between Python 2.x and Python 3.x

Here we will see the differences in the following libraries and modules:

  • Division operator
  • print function
  • Unicode
  • xrange
  • Error Handling
  • _future_ module

Python division operator

If we are porting code or executing Python 3.x code in Python 2.x, it can be dangerous if the change in integer division goes unnoticed (since it does not throw any errors). When porting our code, it's best to use floating point values ​​(such as 7.0/5 or 7/5.0) to get the expected results.

print(7 / 5 )
print(-7 / 5)	
'''
Output in Python 2.x
1
-2

Output in Python 3.x :
1.4
-1.4
'''
  • Print function in Python

    This is the most widely known change. Here, the print keyword in Python 2.x is replaced by the print() function in Python 3.x. However, if you add a space after the print keyword, the parentheses work in Python 2 because the interpreter evaluates it as an expression. You can refer to Printing a Single Multivariable Python for more information on this topic.
    In this example, we can see that if we don't use brackets in python 2.x, then there is no problem, but if we don't use brackets in python 3.x, we get SyntaxError. 

  • 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
    '''
    

    Unicode in Python

    In Python 2, the implicit str type is ASCII. But in Python 3.x, the implicit str type is Unicode. In this example, the differences between Python versions are shown with the help of code and output in Python comments.

  • 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 and range() in two versions

    Python 2.x's xrange() does not exist in Python 3.x. In Python 2.x, range returns a list, i.e. range(3) returns [0,1,2], while xrange returns an xrange object, i.e. xrange(3) returns an iterator object, which works similar to Java iteration processor and generate numbers when needed. 
    If we need to iterate over the same sequence multiple times, we prefer range() because range provides a static list. xrange() rebuilds the sequence every time. xrange() does not support slicing and 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 did in Python 2.x, so to keep the code portable we might want to stick with ranges. So the Python 3.x range function is xrange from Python 2.x. You can refer to this article to learn more about range() and xrange() in Python.

  • 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

    Error handling has changed slightly in both versions. In recent versions of Python, the "as" keyword is optional. 

try:
	trying_to_check_error
except NameError, err:
# Would not work in Python 3.x
	print err, 'Error Caused'

'''
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
'''

In this example, error handling is shown without using the "as" keyword.

try:
	trying_to_check_error
except NameError as err:
	print(err, 'Error Caused')

# code without using as keyword
try:
	trying_to_check_error
	
# 'as' is optional in Python 3.10
except NameError:
	print('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 in Python

This is basically not a difference between the two versions, but a useful thing to mention here. The idea of ​​the __future__ module is to aid migration to Python 3.x. 
If we plan to support Python 3.x in 2.x code, we can use the __future__ import in the code. For example, in the following Python 2.x code, we use the __future__ module to use Python 3.x's integer division behavior. 

# 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

Another example, we use parentheses in Python 2.x using the __future__ module: 

from __future__ import print_function	
print('helloworld')

Output: 

helloworld

Guess you like

Origin blog.csdn.net/arthas777/article/details/133472382