日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python2中的print语句可以不用小括号。_Python 2与Python 3的区别

發布時間:2025/3/20 python 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python2中的print语句可以不用小括号。_Python 2与Python 3的区别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

越來越多的庫要放棄Python 2了,強哥也開始轉向Python 3了。最近的項目開始用Python3寫了,也體會了一下2和3的區別。主要的一些區別在以下幾個方面:

  • print函數
  • 整數相除
  • Unicode
  • 異常處理
  • xrange
  • map函數
  • 不支持has_key

print函數

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

Python 2

print

輸出

hello world

Python 3

print

輸出

hello worldprint

輸出

File "<stdin>", line 1print "hello world"^ SyntaxError: Missing parentheses in call to 'print'

整數相除

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

Python 2

print

輸出

3 / 2 = 1 3 / 2.0 = 1.5

Python 3

print

輸出

3 / 2 = 1.5 3 / 2.0 = 1.5

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

異常處理

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

try

或者

try

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

xrange

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

map函數

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

Python 2

map

輸出

[1, 2, 3, 4, 5]

Python 3

map

輸出

<map object at 0x7ff5b103d2b0>list

輸出

[1, 2, 3, 4, 5]

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

不支持has_key

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

Python 2

person

輸出

person has key "age": True person has key "age": True

Python 3

person

輸出

person has key "age": Trueprint

輸出

Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'has_key'

以上是最近整理的一些,后續會繼續更新,也歡迎大家補充。

總結

以上是生活随笔為你收集整理的python2中的print语句可以不用小括号。_Python 2与Python 3的区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。