python3 x和python2 x区别_Python知识:Python 3.x和2.x版本的使用区别
使用Python時都需要安裝相應的版本,不同的版本適用性也不一樣。
今天從除法算子、打印功能、Unicode、Xrange、錯誤處理、未來模塊方面看看Python2.x和Python3.x之間的區別。
除法算子
在移植代碼或在python2.x中執行python3.x代碼時,要注意整數除法的更改:最好使用浮動值(如7.0/5或7/5.0)來獲得預期的結果。
print 7 / 5
print -7 / 5
'''
Output in Python 2.x
1
-2
Output in Python 3.x :
1.4
-1.4
打印功能
print關鍵字在Python2.x中被打印()函數在Python3.x中。
如果在Python 2之后添加了空格,解釋器將其計算為表達式,則括號在Python 2中起作用。
注意:如果在python 3.x中不使用括號,我們就會得到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:
在Python 2中,隱式str類型是ASCII。
在Python3.x中,隱式str類型是Unicode。
print(type('default string '))
print(type(b'string with b '))
'''
Output in Python 2.x (Bytes is same as str)
Output in Python 3.x (Bytes and str are different)
'''
Python2.x也支持Unicode
print(type('default string '))
print(type(u'string with b '))
'''
Output in Python 2.x (Unicode and str are different)
Output in Python 3.x (Unicode and str are same)
'''
Xrange:
Python2.x的xrange()在Python3.x中不存在。
在Python2.x中,Range返回一個列表,即range(3)返回[0,1,2],
而xrange返回xrange對象,即xrange(3)返回與Java迭代器類似的迭代器對象,并在需要時生成數字。
range()需要多次迭代相同的序列,提供了一個靜態列表。
Xrange()需要每次都重新構造序列。Xrange()不支持片和其他列表方法。
Xrange()的優點:當任務在一個大范圍內迭代時,節省內存。
在Python3.x中,Range函數執行Python2.x中的xrange函數,堅持使用Range保持代碼的可移植性
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
錯誤處理:
在python 3.x中,必須要使用“as”關鍵字。
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
'''
_模塊:
__WORWORY__模塊幫助遷移到Python3.x。
如果想在2.x代碼中支持Python3.x,使用__future__在我們的代碼中導入。
例如,在下面的Python2.x代碼中,我們使用Python3.x的整數除法行為。
# 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
產出:
1.4
-1.4
在Python2.x中使用方括號的另一個例子是_WORWORY__模塊:
from __future__ import print_function
print('GeeksforGeeks')
產出:
GeeksforGeeks
總結
以上是生活随笔為你收集整理的python3 x和python2 x区别_Python知识:Python 3.x和2.x版本的使用区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《小丑2》稳步推进
- 下一篇: DC超英新片《黑亚当》全新海报:巨石强森