python2與python3的區別

1.print()函數

python3的print爲一個函數,使用時必須用括號括起來

python2的print爲一個類。

2.input()函數

python3的input()函數得到一個str數據類型。

Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> 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'>

python2的input()函數得到一個int數據類型。

python2的raw_input()函數得到一個str數據類型。

Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> my_input = input('enter a number: ')
enter a number: 123
>>> type(my_input)
<class 'str'>

3.整除

python3、python2中:

/:表示真除(真實實際結果)

//:表示取整

%:表示去餘

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)
結果:
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0
結果:
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

區別:

在python2中即一個整數(無小數部分的數)被另一個數整除,計算結果的小數部分被截除了。

1/2
結果:
0

4.range()函數

python2中range(0,4)表示[0 , 1 , 2 , 3]

python3中list(range(0 , 4))表示[0 , 1 , 2 , 3]

for i in range(0,4):
    print(i)
結果:
0
1
2
3

5.字符串

python2中字符串用8 bit進行存儲

python3中字符串16 bit unicode進行存儲

6.try ... except ...

python2:

try:
          ......
except    Exception, e :
         ......

python3:

try:
          ......
except    Exception as e :
         ......

7.打開文件

python2用file()或open()打開文件

python3用open()打開文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章