python中print函数的关键字参数

时间:2018-06-26 08:11:47

标签: python

这可能是一个愚蠢的问题,但是我真的不知道哪一部分错了?

我编写了以下代码:

b = 0
while b < 10:
    print(b, end=" ")
    b = b + 1

但是我总是收到此错误消息:

  File "/Users/l/Desktop/test.py", line 3
    print(b, end=" ")
                ^
SyntaxError: invalid syntax

有人可以给我一点帮助吗?谢谢!

4 个答案:

答案 0 :(得分:2)

此语法仅在Python3中有效,您可能正在使用Python2。

Python3:

print("Hello World", end="!") # OUTPUT: Hello World!

Python2:

print("Hello World", end="!")
  

文件“ ... \ python test.py”,第5行       print(“ Hello World”,end =“!”)     SyntaxError:语法无效

答案 1 :(得分:2)

如前所述,这是Python3的功能,但是您也可以在Python2中模拟此行为,如下所示:

from __future__ import print_function

print('Now it works', end='!')

有关未来进口的更多信息,请参见this link

答案 2 :(得分:1)

Python 2和3

from __future__ import print_function

b = 0
while b < 10:
    print(b, end=" ")
    b = b + 1

答案 3 :(得分:1)

在python 3中,您的代码可以正常工作,但是在python 2中,可以这样做:

b = 0
while b < 10:
  print b ,  #put comma at end 
  b = b + 1

0 1 2 3 4 5 6 7 8 9
相关问题