# 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/