Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange error about invalid syntax

Tags:

python

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

like image 884
Sumod Avatar asked Feb 14 '11 10:02

Sumod


People also ask

How do I fix invalid SyntaxError?

You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

Why is my code saying invalid syntax?

The Python SyntaxError occurs when the interpreter encounters invalid syntax in code. When Python code is executed, the interpreter parses it to convert it into bytecode. If the interpreter finds any invalid syntax during the parsing stage, a SyntaxError is thrown.


2 Answers

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.

like image 132
Thuy Avatar answered Sep 20 '22 02:09

Thuy


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.

like image 22
Jonathan Avatar answered Sep 21 '22 02:09

Jonathan