【问题标题】:Python: Unexpected EOF while parsingPython:解析时出现意外的EOF
【发布时间】:2021-03-21 20:24:32
【问题描述】:

我正在编写一个用于制作基于文本的游戏的脚本,我问的任何人都找不到问题,所以我决定在这里问。当它按下回车键时,它会出现 EOF 错误。

代码如下:

import time

print("Welcome to PyGame, a text-based adventure game run entirely via Python version 3.6.8.\n")
start=str(input("Press ENTER to begin."))
if start=="":
    print("Loading...")
    time.sleep(3)
else:
    quit()

具体的错误是:

Welcome to PyGame, a text-based adventure game run entirely via Python version 3.6.8.

Press ENTER to begin.

Traceback (most recent call last):
  File "E:\Random\PyGame.py", line 4, in <module>
    start=str(input("Press ENTER to begin."))
  File "<string>", line 0
    
   ^
SyntaxError: unexpected EOF while parsing

【问题讨论】:

  • 这段代码没有问题,按预期运行。错误在于您没有向我们展示的内容...
  • 你是如何以及在哪里运行这段代码的?
  • 哦,如前所述,这是在 Python 3.6.8 中运行的。
  • IDE?终端?哪一个?笔记本?模拟器?
  • 问题是你实际上运行的是 Python 2,而不是你想象的 3。在 Python 2 中,input 尝试将用户输入的字符串 eval,但由于字符串为空,此处失败。检查您的配置并确保使用 Python 3 运行您的脚本。

标签: python python-2.x eof


【解决方案1】:

在 Python 2.x 中,input() 不会自动评估为 str 类型。因此,当按下Enter 时,它会将输入解释为EOF - 解析时文件结尾,因为没有读取任何内容。

在 Python 3.x 中,input() 函数将空行解析为 str 类型。

您可以尝试在 Python 3.x 中运行游戏。

如果您不能使用 Python 3.x,请尝试使用 try, except 块来捕获并忽略此异常

try:
    start=str(input("Press ENTER to begin."))
except Exception as e:
    start = ""

【讨论】:

  • 捕获Exception 是一个可怕的解决方案。如果您不能使用 Python 3,请使用 raw_input() 而不是 input(),因为这是正确的功能。在 Python 2 中为这个用例使用 input() 是完全错误的。
猜你喜欢
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多