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

标签 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

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

非常感谢您的帮助!

最佳答案

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

# 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 的缩进不匹配

关于Python:为什么我的代码有语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18276058/

相关文章:

python - 如何制作 Python Flickr GUI?

python - 有什么比 Python 中的 Mechanize 更好?

mysql - 从表中选择除同一表中的某些记录之外的所有记录

python - python 中的嵌套 try except

c# - 从字典中取出 n 个元素

python - 尝试/异常(exception)错误Python?

MySQL except 子句不起作用

javascript - Javascript 解析器出现索引错误

python - 如何设置代理隐藏我的IP地址以使用dryscrape抓取网页

python - Djangocollectstatic 无法在 S3 的生产环境中工作,但相同的设置在本地工作