我是python的初学者.我想在控制台中运行这个程序员,但它告诉我错误是什么错误.
>>> def fib(n):
... a, b = 0, 1
... while a < n:
... print (a, end=' ')
File "<stdin>", line 4
print (a, end=' ')
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我的实际程序,我想运行:
>>> def fib(n):
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
>>> fib(1000)
Run Code Online (Sandbox Code Playgroud)
您正在尝试在Python2中运行Python3代码.该Python2print是一个关键字,只是打印什么给了,而Python3print是一些额外的参数的函数.Python3 print被反向移植到Python2,您可以使用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
Run Code Online (Sandbox Code Playgroud)
在纯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
Run Code Online (Sandbox Code Playgroud)
不幸的是,print如果你不打印一个点(print 1, 'something', '.'),Python2会在最后写一个换行符.请参阅如何在没有换行或空格的情况下打印?如何绕过它.
或者您可以存储结果然后连接并立即打印它们,例如:
>>> 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
Run Code Online (Sandbox Code Playgroud)