Strange error regarding invalid syntax

I get an invalid syntax error in my python script for this statement

44 f = open(filename, 'r') 45 return return ^ SyntaxError: invalid syntax 

I'm not sure what is definitely wrong here? I am new to python and will therefore be very grateful if someone can help.

I am using version 2.3.4

+8
python
source share
6 answers

Getting "invalid syntax" in a simple inverse expression is almost impossible. If you use it outside the function, you get a 'return' outside function , if you have the wrong indent, you get an IndentationError , etc.

The only way to get SyntaxError: invalid syntax in the return statement is if it doesn't actually say return at all, but if it contains non-ascii characters like retürn . This will give this error. Now, how can you get this error without seeing it? Again, the only idea I can come up with is that you actually have indentation, but that indentation is not spaces or tabs. For example, you can somehow insert unencrypted space into your code.

Yes it can happen. Yes, it happened to me. Yes, you get SyntaxError: invalid syntax .

+7
source share

I had the same problem. Here is 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' has invalid syntax

I just could not close the bracket with the following code:

 gcpercent = (float(GC)/(totalbases - nbases)*100 

Hope this helps.

+18
source share

I got "Invalid syntax" when returning 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 return syntax.

 ((month2-(month1+1))*30 <---- there should be another bracket ((month2-(month1+1)))*30 

Now my code is working.

They should improve python to tell you if you forgot to close your brackets instead of the "invalid" syntax when returning.

+8
source share

This is usually a summary syntax error. Check the error.

+2
source share

I just looked at this because I had the same problem (incorrect syntax error in the plan return statement) and I am extremely new to python (first month), so I have no idea what I do most of the time.

well, I found my mistake, I forgot the ending parentheses on the previous line. try checking the end of the previous line for forgotten parentheses or quotes?

+2
source share
 >>> 45 return File "<stdin>", line 1 45 return ^ SyntaxError: invalid syntax >>> 

This may explain this. It does not explain 44 f = open(filename, 'r') , but I suspect someone has copied and pasted 45 lines of code where the indentation was lost and line numbers were included.

+1
source share

All Articles