python2 與 python3的區別:
__ future __ 模塊:
python3介紹的一些python2不兼容的關鍵字和特性可以通過在Python2的內置__future__模塊導入,如果在python2中支持python3的代碼,可以導入__future__模塊。
print函數:
- print語法大家都比較熟悉在python2中聲明已經被python3中的print()函數所取代了。在python3中如果使用print將會報錯(SyntaxError)。
python2:
print 'python',python_version()
print 'hello world'
print 'name is',;print 'gallo'
#result:
#python 2.7.6
#hello world
#name is gallo
python3:
print('python',python_version())
print('hello world')
print("name is",end="")
print("gallo")
#reslut:
#python 3.7.1
#hello world
#name is gallo
整除
python3的版本變化中,整數計算可以說是很大的並且可能在移植過程中造成很大的危險。
- 在python2中整除類似於C語言中的整除
python2
>>> 3/2
>>> 3//2
>>> 3/2.0
>>> 3//2.0
#result
# 1
# 1
# 1.5
# 1.0
python3
>>> 3/2
>>> 3//2
>>> 3/2.0
>>> 3//2.0
# reslut
# 1.5
# 1
# 1.5
# 1.0
Unicode
python 2中ASCLL 是字符串類型,Unicode()是單獨的,不是byte類型
現在,在python3有了Unicode(utf-8)字符串,以及一個字節類:byte和bytearrays類型。
由於Python3源碼文件默認使用utf-8編碼,使得變量名爲漢字合法。
>>>梅西 = ‘Messi’
>>>print(梅西)
Messi
python2
>>>str = '梅西'
>>>str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c'
python3
>>> str = "我喜歡踢足球"
>>> str
'我喜歡踢足球'
異常
在python 3中異常做的輕微的改變,使用as作爲關鍵詞。
將捕獲異常的方法從 except exc,var 改爲 except exc as var.
不等運算符
Python 2中不等於有兩種寫法 !=和<>
python 3中去掉了<>,只有!=一種寫法
去掉了repr表達式``
python 2中反引號 `` 相當於repr函數的作用.
python 3只允許使用repr函數.
**repr()**將對象轉化爲供解釋器讀取的形式。
比較不可排序類型
在python3中當不可排序類型作比較的時候,會拋出一個類型錯誤。
python 2
>>> [1,2] > 'foo'
>>>(1,2) > 'foo'
>>>[1,2] > (1,2)
#result
#False
#True
#False
python 3
[1,2] > 'foo'
(1,2)>'foo'
[1,2]>(1,2)
#將會報錯 :不同數據類型之間不能進行比較
next() 函數 and .next()方法
python2方法與函數都可以使用,在python3中使用.next()方法會拋出異常。
input ()和 raw_input()
在python3中input的類型都爲字符串類型,但是在python2中如果輸入123將默認爲int類型,如果要保證輸入的爲字符串類型應該使用的是raw_input()
python 2
>>> my_input = input('enter a number:')
enter a number: 123
>>> type(my_input)
<type 'int'>
>>> my_input = raw_input('enter a number:')
enter a number: 123
>>> type(my_input)
<type 'str'>
python3
#只有input()函數
my_input = input('enter a number')
enter a number: 123
type(my_input)
<type 'str'>