简体   繁体   English

python无效语法错误:打印

[英]python Invalid syntax Error : print

I try to write my first python program.我尝试编写我的第一个 python 程序。 But the print function is very special.但是打印功能很特别。 I tried to write :我试着写:

print ("success!")

very normal.很正常。 but IDLE remind me that the code is wrong and "print" has been red.但IDLE提醒我代码错误,“打印”已红色。 What should I do?我该怎么办?

I think you are just seeing IDLE's syntax-highlighting feature.我认为您只是看到了 IDLE 的语法高亮功能。 Keywords (and function names, variables etc.) are given different colours, in order to make the code easier to read (and spot errors like missing brackets etc.):关键字(和函数名、变量等)被赋予不同的颜色,以便使代码更易于阅读(并发现缺少括号等错误):

If you are seeing the same as this:如果您看到与此相同的内容:

在此处输入图片说明

Then, you have nothing to worry about那你就不用担心了

Assuming this isn't just IDLE's syntax highlighting (hard to tell without the code in question)...假设这不仅仅是 IDLE 的语法突出显示(如果没有相关代码就很难判断)......

The reason for this odd behaviour has to do with a major change that was made in Python 3. In Python 2, print is a keyword.这种奇怪行为的原因与 Python 3 中的重大更改有关。在 Python 2 中, print是一个关键字。 In Python 3, print is a function.在 Python 3 中, print是一个函数。

This has a number of implications:这有很多含义:

  1. In Python3, print requires parentheses在 Python3 中, print需要括号
  2. In Python2, print does not require parentheses by default在 Python2 中, print默认不需要括号
  3. In Python2, print cannot be overridden by default (you cannot change what print does)在 Python2 中,默认情况下无法覆盖print (您无法更改print功能)
  4. In Python3, print can be shadowed in a module, providing different behaviour for one application or another.在 Python3 中, print可以在模块中隐藏,为一个或另一个应用程序提供不同的行为。

Now, what this means is that the syntax by default is different, but the good news is you can get the same syntax on both by putting as the first line in your module:现在,这意味着默认情况下的语法是不同的,但好消息是您可以通过将其作为模块的第一行来获得相同的语法:

from __future__ import print_function

As a side note, this is a good idea since it ensures the same code will run on Python 2.7 and 3. So I add to all my Python modules these days:作为旁注,这是一个好主意,因为它确保相同的代码将在 Python 2.7 和 3 上运行。 所以我现在添加到我所有的 Python 模块中:

from __future__ import print_function, division

(adding division there is good practice because of the way the division operator changed.) (由于除法运算符的变化方式,添加除法是一种很好的做法。)

问题可能出现在print出现在检查中的行中的任何地方,例如,如果您有正确的缩进

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM