1
    # 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!

4
  • Are you mixing tabs and spaces? Commented Aug 16, 2013 at 14:49
  • That's not caused by any of the code you have posted. Post the code that contains the except SyntaxError:. There is probably a missing parenthesis or bracket on the preceding line. Commented Aug 16, 2013 at 14:51
  • @kindall: to my eyes, it looks like the except SyntaxError: line is part of the code for whatever tutorial tool he's using ("learnpythonjail" is suggestive) and not something the OP wrote. Commented Aug 16, 2013 at 14:54
  • This is either a mixing of tabs and spaces, or you are using a character that is blank, but not tab or a space. (Like a non-breaking space, for example). Commented Aug 16, 2013 at 14:55

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.