简体   繁体   中英

Why am I getting an 'Invalid syntax' error after an IF condition?

I have a Python program with an if condition which checks if an item is NOT in the dictionary and throws an error if it is not. Otherwise the code should keep running. However, I receive an 'invalid syntax' error relating to the next line of code after the if condition and I can't understand why. The line of code works fine if run by itself, but not if run together with the if statement. I have multiple exceptions in the program so I do not wish to have them and the remaining code all contained in a hierarchy of elif conditions. To my understanding, I cannot see anything wrong with this code so I would appreciate if anyone can point out what's causing this.

Here's an example piece of code which is also producing the same error and the associated error message.

Code sample:

item = 'a'
item_dict = {
    'a': ['A1','A2','A3'],
    }

if item not in item_dict:
    raise Exception("Error")

# Extract the relevant add on codes from the dictionary.
item_codes = item_dict.get(item)

Error Message:

File "<stdin>", line 5
item_codes = item_dict.get(item)
         ^
SyntaxError: invalid syntax

EDIT: I have fixed typos in the example code and still receive the same syntax error. Note, that the error only occurs if I run this block of code as one. If I run it all, excluding the bottom line which assigns the item_codes variable and then run that line by itself afterwards it is fine and produces the expected results, but the code I'm writing requires being run as one whole program.

You didn't give it a newline after the if block. I did not change anything else and it is working.

item = 'a'
item_dict = {'a': ['A1','A2','A3']}

if item not in item_dict:
    raise Exception("Error")

item_codes = item_dict.get(item)

look at this

>>> if item not in item_dict:
...   print("hi")
... print("hhi")
  File "<stdin>", line 3
    print("hhi")
        ^
SyntaxError: invalid syntax

In the cmd the statement after if is being treated as a part of that if , and so it is expecting a tab.

You need to add a new line , thats it.

The only way i can reproduce your error of syntax is if i leave off a closing brace on the previous line for example

item = 'a'
items_dict = {
    'a': ['A1','A2','A3'],
    }
if item not in items_dict:
    raise Exception("Error"   #here i have left off the closing parenthesis

item_codes = items_dict.get(item)

#ERROR#
  File "<ipython-input-13-919d98974d80>", line 5
    item_codes = items_dict.get(item)
             ^
SyntaxError: invalid syntax

double check the lines before you code to see if you have missed a closing brace or qoute or something

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