Python语法错误print len()

时间:2016-02-11 05:01:08

标签: python liclipse

我是python的新手。我一直在研究Codecademy的课程。我目前也在使用Pydev / LiClipse。

在Codecademy的第一课中,它希望您将变量parrot设置为“Norwegian Blue”。然后它希望你使用len字符串方法打印鹦鹉的长度。这很简单,我马上得到了答案:

parrot = "Norwegian Blue"
print len(parrot)

当我将完全相同的代码放入LiClipse时,它返回:

SyntaxError:语法无效

当我将其更改为:

时,它在LiClipse中工作

print(len(parrot))

有人能让我知道为什么在codecademy中有效,但在LiClipse中没有,为什么添加括号会修复它?

4 个答案:

答案 0 :(得分:3)

听起来Pydev / LiClipse正在使用python 3,而Codeacademy正在使用python 2.7或其他一些旧版本。当python从2.7更新到3时所做的更改之一是使用这样的打印:

print "stuff to be printed"

为:

print("stuff to be printed")

答案 1 :(得分:3)

您必须考虑到您工作的版本。

在Python 2中,您的代码如下所示:

parrot = "Norwegian Blue"
print len(parrot)

在Python 3中,您的代码如下所示:

parrot = "Norwegian Blue"
print ( len(parrot) )

答案 2 :(得分:2)

它在CodeAcademy中有效,因为它们的解释器是Python 2.7,你不需要括号,因为print是一个声明。在Python 3.0+中,print需要括号,因为它是一个函数。

可以在此处找到有关Python 2.7和3.0+之间的不同之处的更多信息:

What's New In Python 3.0

上页中有一些打印样本的差异:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

了解两者之间的差异很有用,以防您使用遗留系统和私有环境中的批次与之比较。在Python 2.7及更低版本中,print()有效;但是,省略()在Python 3.0+中不起作用,所以养成使用它们进行打印的习惯会更好。

Python 2.7的生命周期预计将在2020年结束,所以无论如何你都有充足的时间。

答案 3 :(得分:1)

在Python 3中,print更改为需要括号。 CodeAcademy可能正在使用Python 2,看起来你正在使用Python 3。

https://docs.python.org/3/whatsnew/3.0.html#print-is-a-function

来自文档

  

打印是一种功能   print语句已被替换为   print()函数,用关键字参数替换大部分   旧打印语句的特殊语法(PEP 3105)。例子:

相关问题