python invalid syntax everytime - python

My code always gives invalid syntax errors in different lines. I mean it is giving an error at line 143. Then when I clear that line. It gives the same error at another line. Even I get invalid syntax error at a line like:
print("======================================================================")
How can this be possible? Any ideas?
Thank you ^^

It's hard to know without seeing the whole code. However, be aware that python has implied line continuation with parentheses and other brackets.
This can mean that errors can be reported on a different to that on which the true mistake has been made.
For example:
a = (3 * 4) + (3 * 2
print "Hello"
...gives the error:
File "<ipython-input-1-53e17eda21df>", line 2
print "Hello"
^
SyntaxError: invalid syntax
What is happening is that Python expects the first line to continue, e.g like:
a = (3 * 4) + (3 * 2
+ 100)
...which is completely valid syntax. However, it finds print "Hello" instead, which isn't a valid continuation of the statement inside the brackets.

Related

Using for loops in python interpreter

I'm trying to start a for loop after doing something else in python interpreter on the same line, and it throws a SyntaxError when I do so.
>>> a,b = 0, 1;\
... for i in range(1, 10):
File "<stdin>", line 2
for i in range(1, 10):
^
SyntaxError: invalid syntax
Of course I could just execute them separately here, but if I want to have this inside a function definition then I can't exactly do that. What is the correct syntax to do it in the interpreter?
When you have a backslash, you are telling it to ignore the new line. So Python thought your code was a,b = 0, 1 for i in range(1,10):. This is clearly invalid syntax. So, you must remove the semicolon and the backslash. When you want to go to the new line, use shift + enter key.
After that, it should work:

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

Missleading Python Error Message

If I have a file python_error_msg.py
x = [e for e in range(x)
x+=1
And I run it
$ python3 python_error_msg.py
The missing bracket gives the following error:
File "python_error_msg.py", line 2
x+=1
^
SyntaxError: invalid syntax
Why does it happen this way? My error was in forgetting the ] on the list comprehension. Is this something that could be made better, or is it a deeper matter of how Python syntax works?
Also, where can I look in the
codebase
to get an idea of how error reporting works in Python?
The problem is the error isn't official until that second line. Python keeps reading while inside parentheses (or brackets, braces, etc)
What if your code were this?
x = [e for e in range(x)
]
No error.
That said, in these cases I wish SyntaxError would say:
SyntaxError: invalid syntax on line 2 of parenthetical
(After all, even the most experienced programmers forget to close parentheses sometimes

appending two variables in os.path.isdir

I am trying to append two variables BUILD_ROOT_DIR and W_ROOT and check if this directory exists ,if not raise a flag...running into following syntax error while appending..what is wrong here?
if(os.path.isdir(BUILD_ROOT_DIR + W_ROOT))
raise
if(os.path.isdir(BUILD_ROOT_DIR + W_ROOT))
^
SyntaxError: invalid syntax
You need a colon to end the if statement (the parentheses are not required):
if os.path.isdir(BUILD_ROOT_DIR + W_ROOT):
raise
God gave you ':' for ending an if clause and he also told you: keep this Python tutorial under your pillow and read it all night before sleeping.
http://docs.python.org/2/tutorial/controlflow.html#if-statements

Strange error about invalid syntax

I am getting invalid syntax error in my python script for this statement
44 f = open(filename, 'r')
45 return
return
^
SyntaxError: invalid syntax
I am not sure what exactly is wrong here? I am a python newbie and so will greatly appreciate if someone can please help.
I am using version 2.3.4
I had the same problem. Here was my code:
def gccontent(genomefile):
nbases = 0
totalbases = 0
GC = 0
for line in genomefile.xreadlines():
nbases += count(seq, 'N')
totalbases += len(line)
GC += count(line, 'G' or 'C')
gcpercent = (float(GC)/(totalbases - nbases)*100
return gcpercent
'return'was invalid syntax
I simply failed to close the bracket on the following code:
gcpercent = (float(GC)/(totalbases - nbases)*100
Hope this helps.
I got an "Invalid Syntax" on return when I forgot to close the bracket on my code.
elif year1==year2 and month1 != month2:
total_days = (30-day1)+(day2)+((month2-(month1+1))*30
return (total_days)
Invalid syntax on return.
((month2-(month1+1))*30 <---- there should be another bracket
((month2-(month1+1)))*30
Now my code works.
They should improve python to tell you if you forgot to close your brackets instead of having an "invalid" syntax on return.
Getting "invalid syntax" on a plain return statement is pretty much impossible. If you use it outside of a function, you get 'return' outside function, if you have the wrong indentation you get IndentationError, etc.
The only way I can get a SyntaxError: invalid syntax on a return statement, is if in fact it doesn't say return at all, but if it contains non-ascii characters, such as retürn. That give this error. Now, how can you have that error without seeing it? Again, the only idea I can come up with is that you in fact have indentation, but that this indentation is not spaces or tabs. You can for example have somehow inserted a non-breaking space in your code.
Yes, this can happen. Yes, I have had that happen to me. Yes, you get SyntaxError: invalid syntax.
i just looked this up because i was having the same problem (invalid syntax error on plan return statement), and i am extremely new at python (first month) so i have no idea what i'm doing most of the time.
well i found my error, i had forgotten an ending parentheses on the previous line. try checking the end of the previous line for a forgotten parentheses or quote?
>>> 45 return
File "<stdin>", line 1
45 return
^
SyntaxError: invalid syntax
>>>
That might explain it. It doesn't explain the 44 f = open(filename, 'r'), but I suspect that someone copied and pasted 45 lines of code where the indentation was lost and line numbers included.
Usually it's a parenthetical syntax error. Check around the error.
I encountered a similar problem by trying to return a simple variable assignation within an "if" block.
elif len(available_spots)==0:
return score=0
That would give me a syntax error. I fixed it simply by adding a statement before the return
elif len(available_spots)==0:
score=0
return score
I had the same problem. The issue in my case was, that i mixed up datatypes in my return statement. E.g.
return string + list + string

Categories

Resources