我是 python 初学者。我想在控制台中运行这个程序员,但它告诉我错误是什么错误。
>>> def fib(n):
... a, b = 0, 1
... while a < n:
... print (a, end=' ')
File "<stdin>", line 4
print (a, end=' ')
^
SyntaxError: invalid syntax
我要运行的实际程序:
>>> def fib(n):
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
>>> fib(1000)
最佳答案
您正在尝试在 Python2 中运行 Python3 代码。 Python2 print
是一个关键字,只打印给定的内容,而 Python3 print
是一个带有一些附加参数的函数。 Python3 print
was backported to Python2 and you can made it available using from __future__ import print_function
:
>>> from __future__ import print_function
>>> def fib(n):
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> fib(5)
0 1 1 2 3
在普通的 Python2 中它看起来像这样:
>>> def fib(n):
... a, b = 0, 1
... while a < n:
... print a, ' '
... a, b = b, a + b
... print
...
>>> fib(5)
0
1
1
2
3
不幸的是,如果您不打印点 (print 1, 'something', '.'
),Python2 print
会在末尾写一个换行符。参见 How to print without newline or space?寻找绕过它的方法。
或者您可以只存储结果,然后连接并立即打印它们,例如:
>>> def fib(n):
... a, b = 0, 1
... results = []
... while a < n:
... result.append(a)
... a, b = b, a + b
... print ' '.join([str(r) for r in results])
...
>>> fib(5)
0 1 1 2 3
关于python - 尝试在 python 中运行这个 progrmmer(控制台)但显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24772106/