亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python中,“SyntaxError:在調用‘print’時缺少括號”意味著什么?

在Python中,“SyntaxError:在調用‘print’時缺少括號”意味著什么?

慕容708150 2019-06-05 16:20:26
在Python中,“SyntaxError:在調用‘print’時缺少括號”意味著什么?當我試圖使用print語句,它給出了以下錯誤:>>> print "Hello, World!"   File "<stdin>", line 1     print "Hello, World!"                         ^SyntaxError: Missing parentheses in call to 'print'那是什么意思?
查看完整描述

3 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

此錯誤消息意味著您正在嘗試使用Python 3來遵循一個示例或運行使用Python 2的程序。print聲明:

print "Hello, World!"

上面的語句在Python 3中不起作用。在Python 3中,需要在要打印的值周圍添加括號:

print("Hello, World!")

“SyntaxError:調用‘print’時缺少括號”是在Python3.4.2中添加的一條新錯誤消息,主要是為了幫助那些在運行Python 3時試圖遵循Python 2教程的用戶。

在Python 3中,打印值從單獨的語句變為普通的函數調用,因此現在需要括號:

>>> print("Hello, World!")Hello, World!

在早期版本的Python 3中,解釋器只報告一個泛型語法錯誤,而沒有提供任何有用的提示,說明可能出錯的地方:

>>> print "Hello, World!"
  File "<stdin>", line 1
    print "Hello, World!"
                        ^SyntaxError: invalid syntax

至于為什么 print在Python 3中,它變成了一個普通的函數,它與語句的基本形式無關,而是與如何執行更復雜的操作有關,比如將多個項打印到帶有尾部空格的stderr,而不是結束行。

在Python 2中:

>>> import sys>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 61 2 3 4 5 6

在Python 3中:

>>> import sys>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)1 2 3 4 5 6

從2017年9月的Python3.6.3發行版開始,已經更新了一些與Python2.x打印語法相關的錯誤消息,以推薦它們的Python3.x對應項:

>>> print "Hello!"
  File "<stdin>", line 1
    print "Hello!"
                 ^SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?

由于“調用打印中缺少的括號”是編譯時語法錯誤,因此可以訪問原始源代碼,因此可以在建議的替換中包含行的其余部分的全文。然而,它目前并沒有試圖找出適當的引號來圍繞這個表達式(這并不是不可能的,只是足夠復雜,以至于還沒有完成)。

這個TypeError還為右班操作員定制了:

>>> print >> sys.stderrTraceback (most recent call last):
  File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. 
  Did you mean "print(<message>, file=<output_stream>)"?

由于此錯誤是在代碼運行時引發的,而不是在編譯時引發的,因此它無法訪問原始源代碼,因此使用元變量(<message><output_stream>)在建議的替換表達式中,而不是用戶實際鍵入的任何內容。與語法錯誤情況不同,在自定義右移位錯誤消息中放置Python表達式周圍的引號非常簡單。


查看完整回答
反對 回復 2019-06-05
?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

語法從Python 2更改為Python 3。在Python 2中,

print "Hello, World!"

將起作用,但在Python 3中,使用括號作為

print("Hello, World!")

這相當于Scala和Java的語法。


查看完整回答
反對 回復 2019-06-05
?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

如果您的代碼應該同時在Python 2和3中工作,您可以通過在程序開始時加載它來實現這一點:

from __future__ import print_function   # If code has to work in Python 2 and 3!

然后您可以Python 3方式打?。?/trans>

print("python")

如果您想在不創建新行的情況下打印某些內容,可以這樣做:

for number in range(0, 10):
    print(number, end=', ')


查看完整回答
反對 回復 2019-06-05
  • 3 回答
  • 0 關注
  • 1434 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號