简体   繁体   中英

Python: Why does my code have a syntax error?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM