python3 x和python2 x区别_Python知识:Python 3.x和2.x版本的使用区别
使用Python時(shí)都需要安裝相應(yīng)的版本,不同的版本適用性也不一樣。
今天從除法算子、打印功能、Unicode、Xrange、錯(cuò)誤處理、未來模塊方面看看Python2.x和Python3.x之間的區(qū)別。
除法算子
在移植代碼或在python2.x中執(zhí)行python3.x代碼時(shí),要注意整數(shù)除法的更改:最好使用浮動(dòng)值(如7.0/5或7/5.0)來獲得預(yù)期的結(jié)果。
print 7 / 5
print -7 / 5
'''
Output in Python 2.x
1
-2
Output in Python 3.x :
1.4
-1.4
打印功能
print關(guān)鍵字在Python2.x中被打印()函數(shù)在Python3.x中。
如果在Python 2之后添加了空格,解釋器將其計(jì)算為表達(dá)式,則括號(hào)在Python 2中起作用。
注意:如果在python 3.x中不使用括號(hào),我們就會(huì)得到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返回一個(gè)列表,即range(3)返回[0,1,2],
而xrange返回xrange對(duì)象,即xrange(3)返回與Java迭代器類似的迭代器對(duì)象,并在需要時(shí)生成數(shù)字。
range()需要多次迭代相同的序列,提供了一個(gè)靜態(tài)列表。
Xrange()需要每次都重新構(gòu)造序列。Xrange()不支持片和其他列表方法。
Xrange()的優(yōu)點(diǎn):當(dāng)任務(wù)在一個(gè)大范圍內(nèi)迭代時(shí),節(jié)省內(nèi)存。
在Python3.x中,Range函數(shù)執(zhí)行Python2.x中的xrange函數(shù),堅(jiān)持使用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
錯(cuò)誤處理:
在python 3.x中,必須要使用“as”關(guān)鍵字。
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__在我們的代碼中導(dǎo)入。
例如,在下面的Python2.x代碼中,我們使用Python3.x的整數(shù)除法行為。
# 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
產(chǎn)出:
1.4
-1.4
在Python2.x中使用方括號(hào)的另一個(gè)例子是_WORWORY__模塊:
from __future__ import print_function
print('GeeksforGeeks')
產(chǎn)出:
GeeksforGeeks
總結(jié)
以上是生活随笔為你收集整理的python3 x和python2 x区别_Python知识:Python 3.x和2.x版本的使用区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《小丑2》稳步推进
- 下一篇: python中func函数用法_pyth