Python 2.7版本與3.6的不同__Python

來源:互聯網
上載者:User

許多Python初學者都會問:我應該學習哪個版本的Python。對於這個問題,我的回答通常是“先選擇一個最適合你的Python教程,教程中使用哪個版本的Python,你就用那個版本。等學得差不多了,再來研究不同版本之間的差別”。

許多Python初學者都會問:我應該學習哪個版本的Python。對於這個問題,我的回答通常是“先選擇一個最適合你的Python教程,教程中使用哪個版本的Python,你就用那個版本。等學得差不多了,再來研究不同版本之間的差別”。

但如果想要用Python開發一個新項目,那麼該如何選擇Python版本呢。我可以負責任的說,大部分Python庫都同時支援Python 2.7.x和3.x版本的,所以不論選擇哪個版本都是可以的。但為了在使用Python時避開某些版本中一些常見的陷阱,或需要移植某個Python項目時,依然有必要瞭解一下Python兩個常見版本之間的主要區別。

__future__模組

Python 3.x引入了一些與Python 2不相容的關鍵字和特性,在Python 2中,可以通過內建的__future__模組匯入這些新內容。如果你希望在Python 2環境下寫的代碼也可以在Python 3.x中運行,那麼建議使用__future__模組。例如,如果希望在Python 2中擁有Python 3.x的整數除法行為,可以通過下面的語句匯入相應的模組。

                  from __future__ import division         

下表列出了__future__中其他可匯入的特性:

特性 可選版本 強製版本 效果
nested_scopes 2.1.0b1 2.2 PEP 227:Statically Nested Scopes
generators 2.2.0a1 2.3 PEP 255:Simple Generators
division 2.2.0a2 3.0 PEP 238:Changing the Division Operator
absolute_import 2.5.0a1 3.0 PEP 328:Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6 PEP 343:The “with” Statement
print_function 2.6.0a2 3.0 PEP 3105:Make print a function
unicode_literals 2.6.0a2 3.0 PEP 3112:Bytes literals in Python 3000

(來源: https://docs.python.org/2/library/future.html)

樣本:

                  from platform import python_version         

print函數

雖然print文法是Python 3中一個很小的改動,且應該已經廣為人知,但依然值得提一下:Python 2中的print語句被Python 3中的print()函數取代,這意味著在Python 3中必須用括弧將需要輸出的對象括起來。

在Python 2中使用額外的括弧也是可以的。但反過來在Python 3中想以Python2的形式不帶括弧調用print函數時,會觸發SyntaxError。

Python 2

                  print 'Python', python_version()           print 'Hello, World!'           print('Hello, World!')           print "text", ; print 'print more text on the same line'         
                  Python 2.7.6           Hello, World!           Hello, World!           text print more text on the same line         

Python 3

                  print('Python', python_version())           print('Hello, World!')                      print("some text,", end="")            print(' print more text on the same line')         
                  Python 3.4.1           Hello, World!           some text, print more text on the same line         
                  print 'Hello, World!'         
                  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.