Python 應用領域以及版本之間的區別

Python 應用領域以及版本之間的區別

一.Python應用領域

  1. Python+人工智能,給你更多研究方向選擇!
    在這裏插入圖片描述
  2. 企業級綜合實戰項目,集六大前沿技術爲一體

二. Python 2與Python 3的區別

Python 2與Python3的區別。主要體現在以下幾個方面:

· print函數

· 整數相除

· Unicode

· 異常處理

· xrange

· map函數

· 不支持has_key

  1. print函數

Python 2中print是語句(statement),Python 3中print則變成了函數。在Python 3中調用print需要加上括號,不加括號會報SyntaxError

Python 2

print “hello world”

輸出

hello world

Python 3

print(“hello world”)

輸出

hello world

print “hello world”

輸出

File “”, line 1

print "hello world"

SyntaxError: Missing parentheses in call to ‘print’

  1. 整數相除

在Python 2中,3/2的結果是整數,在Python 3中,結果則是浮點數

Python 2

print ‘3 / 2 =’, 3 / 2

print ‘3 / 2.0 =’, 3 / 2.0

輸出

3 / 2 = 1

3 / 2.0 = 1.5

Python 3

print(‘3 / 2 =’, 3 / 2)

print(‘3 / 2.0 =’, 3 / 2.0)

輸出

3 / 2 = 1.5

3 / 2.0 = 1.5

  1. Unicode

Python 2有兩種字符串類型:str和unicode,Python 3中的字符串默認就是Unicode,Python 3中的str相當於Python 2中的unicode。

在Python 2中,如果代碼中包含非英文字符,需要在代碼文件的最開始聲明編碼,如下

-- coding: utf-8 --

在Python 3中,默認的字符串就是Unicode,就省去了這個麻煩,下面的代碼在Python 3可以正常地運行

a = “你好”

print(a)

  1. 異常處理

Python 2中捕獲異常一般用下面的語法

try:

1/0 

except ZeroDivisionError, e:

print str(e)

或者

try:

1/0 

except ZeroDivisionError as e:

print str(e)

Python 3中不再支持前一種語法,必須使用as關鍵字。

  1. xrange

Python 2中有 range 和 xrange 兩個方法。其區別在於,range返回一個list,在被調用的時候即返回整個序列;xrange返回一個iterator,在每次循環中生成序列的下一個數字。Python 3中不再支持 xrange 方法,Python 3中的 range 方法就相當於 Python 2中的 xrange 方法。

  1. map函數

在Python 2中,map函數返回list,而在Python 3中,map函數返回iterator。

Python 2

map(lambda x: x+1, range(5))

輸出

[1, 2, 3, 4, 5]

Python 3

map(lambda x: x+1, range(5))

輸出

<map object at 0x7ff5b103d2b0>

list(map(lambda x: x+1, range(5)))

輸出

[1, 2, 3, 4, 5]

filter函數在Python 2和Python 3中也是同樣的區別。

  1. 不支持has_key

Python 3中的字典不再支持has_key方法

Python 2

person = {“age”: 30, “name”:
“Xiao Wang”}

print "person has key “age”: ", person.has_key(“age”)

print "person has key “age”: ", “age” in person

輸出

person has key “age”: True

person has key “age”: True

Python 3

person = {“age”: 30, “name”: “Xiao Wang”}

print("person has key “age”: ", “age” in person)

輸出

person has key “age”: True

print(“person has key"age”: ", person.has_key(“age”))

輸出

Traceback (most recent call last):

File “”, line 1, in

AttributeError: ‘dict’ object has no attribute ‘has_key’

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