在Python中我放了print()但仍然出现语法错误

vin*_*ent 0 python syntax-error

我在这里读了一些关于print()括号的答案.无论如何我放了它们并得到语法错误.你能说出原因吗?

Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
[GCC 4.8.1] on linux



>>> answer = "no"
>>> while answer == "no":
...     answer = input("Are we there? ")
... print("We're there!")
  File "<stdin>", line 3
    print("We're there!")
        ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

是的,我可以看到...提示将打印线保持在while循环下.如果我按2次Enter,则从输入中打印字符串.

>>> answer = "no"
>>> while answer == "no":
...     answer = input("Are we there? ")
... 
Are we there?
Run Code Online (Sandbox Code Playgroud)

ada*_*rsh 7

好吧,因为你在翻译中,你可以再次看到3个点,这意味着它仍然期望它在while循环中.只需再次按Enter即可.但是如果您希望打印件成为循环的一部分,请缩进它,按Enter键并再次按Enter键.希望这可以帮助!

1: >>> answer = "no"
2: >>> while answer == "no":
3: ...     answer = input("Are we there? ")
4: ... 
5: Are we there? no
6: Are we there? yes
7: >>>
Run Code Online (Sandbox Code Playgroud)

在第2行,您开始循环.在第3行,您说stdin的输入将存储在answer.但输入所采用的参数是将提示使用的消息.在第4行,解释器仍然期望循环中的某些东西.如果你有一个缩进块,它就是循环的一部分.如果按Enter键,则完成循环

注意:这是一个解释器,它现在有整个while块可以执行,所以它执行.

在第5行,它正在执行循环并等待您的输入(并且还显示了正确的消息)

您输入'no'作为输入.它不会中断循环,因此它再次执行循环并再次请求输入.现在把'no'它打开然后你再次得到提示,因为解释器没有任何东西可以执行(还).

  • @vincent,因为你在翻译中,你不能同时运行这两个语句!它将运行`while`循环,因为这是代码的所有"块",但你不能放任何东西.尝试将整个事物包装在一个函数中,然后调用该函数. (3认同)
  • @vincent您需要将其作为脚本运行或将while循环放入函数中. (2认同)