Python:为什么我的代码有语法错误?

时间:2013-08-16 14:46:54

标签: python except

    # Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}

def get_last_name():
    try:
        return actor["last_name"]
    except KeyError:
        return "Cleese"

#Test code
get_last_name()
print "All exceptions caught! Good job!"
print "The actor's last name is %s" % get_last_name()

大家好,请你告诉我为什么会收到这个错误:

Traceback (most recent call last):
  File "/base/data/home/apps/s~learnpythonjail/3.368780930138799213/main.py", line 77, in execute_python
    exec(code, {})
  File "<string>", line 9
    except SyntaxError:
         ^
SyntaxError: invalid syntax

我尝试了所有类型的错误捕获,但仍然会产生语法错误。

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

你正在混合制表符和空格。您的代码是:

# Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}

def get_last_name():
····try:
····――――――return actor["last_name"]
――――――except KeyError:
········return "Cleese"

#Test code
get_last_name()
print "All exceptions caught! Good job!"
print "The actor's last name is %s" % get_last_name()

其中――――――表示标签,·表示空格。我故意将选项卡表示为6个字符宽,因为4只是你的编辑器使用的约定。使用制表符或空格进行缩进,但不要混合它们! PEP8提倡空格。

在这种情况下,问题是try的缩进与except

的缩进不匹配

答案 1 :(得分:0)

我只是复制并粘贴你的代码,我没有错误,这意味着它可能是一个布局错误。如果您正在使用标签,请尝试删除它们并用4个空格替换它们。

相关问题