Python程序出现“unexpected EOF while parsing”错误,如何排查和解决?

catNames = []

while True:
print(‘please enter the name of your cat:’)
name = str(input())
if name == str():
break
catNames = catNames + [name]

print(‘the cas name are:’ + catNames )
——————————————————————————
报错:
Traceback (most recent call last):
File “/Users/mrdongzhijie/Python/statisc-c4.py”, line 5, in <module>
name = input()
File “<string>”, line 0


^
SyntaxError: unexpected EOF while parsing
——————————————————————
附加问题:
为毛代码已经将输入转换为 str,结果在交互环境输入字符时还要加‘’,否则就要报错?
Python程序出现“unexpected EOF while parsing”错误,如何排查和解决?


13 回复

raw_input


这个错误通常是因为Python解释器在解析代码时,遇到了不完整的语法结构,比如缺少括号、引号或者冒号。我来给你几个常见的排查方向。

首先,检查你最近修改的代码行。最常见的原因是:

  1. 括号、方括号或花括号没有闭合
  2. 字符串引号没有配对
  3. 复合语句(如if、for、def)后面缺少冒号
  4. 多行语句(如列表、字典)在中间意外结束

举个例子,下面这段代码就会报这个错:

def my_function():
    print("Hello"  # 这里缺少右括号

# 或者这样
my_list = [1, 2, 3  # 缺少右方括号

修复很简单,把缺失的部分补上就行:

def my_function():
    print("Hello")  # 加上右括号

my_list = [1, 2, 3]  # 加上右方括号

如果你在写多行表达式,确保使用反斜杠或者括号来明确表示代码还没结束:

# 正确的方式
result = (value1 + 
          value2 + 
          value3)

建议用IDE的括号高亮功能来辅助检查。

先问一下,你用的 Python 是什么版本?教材上说的是什么版本?

你需要游标卡尺

从 sublime 复制过来的,缩进是没问题的啊 ==

用的 3.6 教材上估计用的 3.4. 反正都是 3.x 应该不会是版本问题吧

3.x 版本不是整合了 raw_input( ) 和 input ()嘛?

cute 的正解

重新用手打意边,缩进的问题

O(∩_∩)O

论 pep8 的重要性

我错了……复制过程出错……求大神轻拍==

回到顶部