Reputation: 69
# 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()
Hi guys, could you please tell me why I got this error:
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
I tried all types of error catching and it still produces a syntax error.
Thanks a lot for any help!
Upvotes: 1
Views: 2456
Reputation: 97601
You're mixing tabs and spaces. Your code is:
# 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()
where ――――――
represents a tab, and ·
a space. I've intentionally represented the tab as 6 characters wide, because 4 is only the convention your editor is using. Either use tabs or spaces for indentation, but do not mix them! PEP8 advocates spaces.
In this case, the problem is that the indentation of the try
does not match that of the except
Upvotes: 4
Reputation: 806
I just copy and pasted your code and I get no errors which means it is likely a layout error. If you are using tabs try removing them and replacing them with 4 spaces.
Upvotes: 0