My question concern the code that was posted in this question Questions about a tic-tac-toe program I am writing.
More precisely this line:
stop = int(0)# 0 = continue
First I didn't understand what he was trying to do and thought that it was a SyntaxError. But when I tried to execute this line, it didn't raise a SyntaxError, it just set stop to 0. Note this line is not inside a loop.
>>> stop = int(0)# 0 = continue
>>> stop
0
But this, as I expected, raise a error:
>>> int(0) = continue
File "<stdin>", line 1
int(0) = continue
^
SyntaxError: invalid syntax
Do someone know why that line is valied, thanx.
# introduces a comment. Everything after it is a comment and has no meaning to the Python interpreter. The comment is likely trying to say "zero means to continue".
PEP8 advises that "inline comments should be separated by at least two spaces from the statement", which would probably have removed some confusion here.
Related
I have this code:
def Psat(self, T):
pop= self.getPborder(T)
boolean=int(pop[0])
P1=pop[1]
P2=pop[2]
if boolean:
Pmin = float(min([P1, P2]))
Pmax = float(max([P1, P2]))
Tr=T/self.typeMolecule.Tc
w=0.5*(1+scipy.tanh((10**5)*(Tr-0.6)))
fi1=0.5*(1-scipy.tanh(8*((Tr**0.4)-1)))
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
guess = Pmin+(Pmax-Pmin)*((1-w**2)*fi1+(w**2)*fi2) # error here
solution = scipy.optimize.newton(funcPsat,guess, args=(T,self))
On the marked line of code, guess = Pmin+(Pmax-Pmin)*((1-w**2)*fi1+(w**2)*fi2), I get an error message: SyntaxError: invalid syntax.
Pmin, Pmax, w, fi1 and fi2 have all been assigned at this point, so why is there an error?
When I remove that line from the code, the same error appears at the next line of code, again for no apparent reason.
When an error is reported on a line that appears correct, try removing (or commenting out) the line where the error appears to be. If the error moves to the next line, there are two possibilities:
Either both lines have a problem (and the second may have been hidden by the first); or
The previous line has a problem which is being carried forward.
The latter is more likely, especially if removing another line causes the error to move again.
For example, code like the following, saved as twisty_passages.py:
xyzzy = (1 +
plugh = 7
will produce an error on line 2, even though the problem is clearly caused by line 1:
File "twisty_passages.py", line 2
plugh = 7
^
SyntaxError: invalid syntax
The code in the question has a similar problem: the code on the previous line has unbalanced parentheses. Annotated to make it clearer:
# open parentheses: 1 2 3
# v v v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
# ^ ^
# close parentheses: 1 2
There isn't really a general solution for this - the code needs to be analyzed and understood, in order to determine how the parentheses should be altered.
You're missing a close paren in this line:
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
There are three ( and only two ).
I encountered a similar problem, with a syntax error that I knew should not be a syntax error. In my case it turned out that a Python 2 interpreter was trying to run Python 3 code, or vice versa; I think that my shell had a PYTHONPATH with a mixture of Python 2 and Python 3.
I noticed that invalid syntax error for no apparent reason can be caused by using space in:
print(f'{something something}')
Python IDLE seems to jump and highlight a part of the first line for some reason (even if the first line happens to be a comment), which is misleading.
I have this code:
def Psat(self, T):
pop= self.getPborder(T)
boolean=int(pop[0])
P1=pop[1]
P2=pop[2]
if boolean:
Pmin = float(min([P1, P2]))
Pmax = float(max([P1, P2]))
Tr=T/self.typeMolecule.Tc
w=0.5*(1+scipy.tanh((10**5)*(Tr-0.6)))
fi1=0.5*(1-scipy.tanh(8*((Tr**0.4)-1)))
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
guess = Pmin+(Pmax-Pmin)*((1-w**2)*fi1+(w**2)*fi2) # error here
solution = scipy.optimize.newton(funcPsat,guess, args=(T,self))
On the marked line of code, guess = Pmin+(Pmax-Pmin)*((1-w**2)*fi1+(w**2)*fi2), I get an error message: SyntaxError: invalid syntax.
Pmin, Pmax, w, fi1 and fi2 have all been assigned at this point, so why is there an error?
When I remove that line from the code, the same error appears at the next line of code, again for no apparent reason.
When an error is reported on a line that appears correct, try removing (or commenting out) the line where the error appears to be. If the error moves to the next line, there are two possibilities:
Either both lines have a problem (and the second may have been hidden by the first); or
The previous line has a problem which is being carried forward.
The latter is more likely, especially if removing another line causes the error to move again.
For example, code like the following, saved as twisty_passages.py:
xyzzy = (1 +
plugh = 7
will produce an error on line 2, even though the problem is clearly caused by line 1:
File "twisty_passages.py", line 2
plugh = 7
^
SyntaxError: invalid syntax
The code in the question has a similar problem: the code on the previous line has unbalanced parentheses. Annotated to make it clearer:
# open parentheses: 1 2 3
# v v v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
# ^ ^
# close parentheses: 1 2
There isn't really a general solution for this - the code needs to be analyzed and understood, in order to determine how the parentheses should be altered.
You're missing a close paren in this line:
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
There are three ( and only two ).
I encountered a similar problem, with a syntax error that I knew should not be a syntax error. In my case it turned out that a Python 2 interpreter was trying to run Python 3 code, or vice versa; I think that my shell had a PYTHONPATH with a mixture of Python 2 and Python 3.
I noticed that invalid syntax error for no apparent reason can be caused by using space in:
print(f'{something something}')
Python IDLE seems to jump and highlight a part of the first line for some reason (even if the first line happens to be a comment), which is misleading.
It is very similar to this:
How to tell if a string contains valid Python code
The only difference being instead of the entire program being given altogether, I am interested in a single line of code at a time.
Formally, we say a line of python is "syntactically valid" if there exists any syntactically valid python program that uses that particular line.
For instance, I would like to identify these as syntactically valid lines:
for i in range(10):
x = 1
Because one can use these lines in some syntactically valid python programs.
I would like to identify these lines as syntactically invalid lines:
for j in range(10 in range(10(
x =++-+ 1+-
Because no syntactically correct python programs could ever use these lines
The check does not need to be too strict, it just need to be good enough to filter out obviously bogus statements (like the ones shown above). The line is given as a string, of course.
This uses codeop.compile_command to attempt to compile the code. This is the same logic that the code module does to determine whether to ask for another line or immediately fail with a syntax error.
import codeop
def is_valid_code(line):
try:
codeop.compile_command(line)
except SyntaxError:
return False
else:
return True
It can be used as follows:
>>> is_valid_code('for i in range(10):')
True
>>> is_valid_code('')
True
>>> is_valid_code('x = 1')
True
>>> is_valid_code('for j in range(10 in range(10(')
True
>>> is_valid_code('x = ++-+ 1+-')
False
I'm sure at this point, you're saying "what gives? for j in range(10 in range(10( was supposed to be invalid!" The problem with this line is that 10() is technically syntactically valid, at least according to the Python interpreter. In the REPL, you get this:
>>> 10()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
10()
TypeError: 'int' object is not callable
Notice how this is a TypeError, not a SyntaxError. ast.parse says it is valid as well, and just treats it as a call with the function being an ast.Num.
These kinds of things can't easily be caught until they actually run.
If some kind of monster managed to modify the value of the cached 10 value (which would technically be possible), you might be able to do 10(). It's still allowed by the syntax.
What about the unbalanced parentheses? This fits the same bill as for i in range(10):. This line is invalid on its own, but may be the first line in a multi-line expression. For example, see the following:
>>> is_valid_code('if x ==')
False
>>> is_valid_code('if (x ==')
True
The second line is True because the expression could continue like this:
if (x ==
3):
print('x is 3!')
and the expression would be complete. In fact, codeop.compile_command distinguishes between these different situations by returning a code object if it's a valid self-contained line, None if the line is expected to continue for a full expression, and throwing a SyntaxError on an invalid line.
However, you can also get into a much more complicated problem than initially stated. For example, consider the line ). If it's the start of the module, or the previous line is {, then it's invalid. However, if the previous line is (1,2,, it's completely valid.
The solution given here will work if you only work forward, and append previous lines as context, which is what the code module does for an interactive session. Creating something that can always accurately identify whether a single line could possibly exist in a Python file without considering surrounding lines is going to be extremely difficult, as the Python grammar interacts with newlines in non-trivial ways. This answer responds with whether a given line could be at the beginning of a module and continue on to the next line without failing.
It would be better to identify what the purpose of recognizing single lines is and solve that problem in a different way than trying to solve this for every case.
I am just suggesting, not sure if going to work... But maybe something with exec and try-except?
code_line += "\n" + ("\t" if code_line[-1] == ":" else "") + "pass"
try:
exec code_line
except SyntaxError:
print "Oops! Wrong syntax..."
except:
print "Syntax all right"
else:
print "Syntax all right"
Simple lines should cause an appropriate answer
I have this code:
def Psat(self, T):
pop= self.getPborder(T)
boolean=int(pop[0])
P1=pop[1]
P2=pop[2]
if boolean:
Pmin = float(min([P1, P2]))
Pmax = float(max([P1, P2]))
Tr=T/self.typeMolecule.Tc
w=0.5*(1+scipy.tanh((10**5)*(Tr-0.6)))
fi1=0.5*(1-scipy.tanh(8*((Tr**0.4)-1)))
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
guess = Pmin+(Pmax-Pmin)*((1-w**2)*fi1+(w**2)*fi2) # error here
solution = scipy.optimize.newton(funcPsat,guess, args=(T,self))
On the marked line of code, guess = Pmin+(Pmax-Pmin)*((1-w**2)*fi1+(w**2)*fi2), I get an error message: SyntaxError: invalid syntax.
Pmin, Pmax, w, fi1 and fi2 have all been assigned at this point, so why is there an error?
When I remove that line from the code, the same error appears at the next line of code, again for no apparent reason.
When an error is reported on a line that appears correct, try removing (or commenting out) the line where the error appears to be. If the error moves to the next line, there are two possibilities:
Either both lines have a problem (and the second may have been hidden by the first); or
The previous line has a problem which is being carried forward.
The latter is more likely, especially if removing another line causes the error to move again.
For example, code like the following, saved as twisty_passages.py:
xyzzy = (1 +
plugh = 7
will produce an error on line 2, even though the problem is clearly caused by line 1:
File "twisty_passages.py", line 2
plugh = 7
^
SyntaxError: invalid syntax
The code in the question has a similar problem: the code on the previous line has unbalanced parentheses. Annotated to make it clearer:
# open parentheses: 1 2 3
# v v v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
# ^ ^
# close parentheses: 1 2
There isn't really a general solution for this - the code needs to be analyzed and understood, in order to determine how the parentheses should be altered.
You're missing a close paren in this line:
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
There are three ( and only two ).
I encountered a similar problem, with a syntax error that I knew should not be a syntax error. In my case it turned out that a Python 2 interpreter was trying to run Python 3 code, or vice versa; I think that my shell had a PYTHONPATH with a mixture of Python 2 and Python 3.
I noticed that invalid syntax error for no apparent reason can be caused by using space in:
print(f'{something something}')
Python IDLE seems to jump and highlight a part of the first line for some reason (even if the first line happens to be a comment), which is misleading.
I am very new to python, this is my first program that I am trying.
This function reads the password from the standard input.
def getPassword() :
passwordArray =[]
while 1:
char = sys.stdin.read(1)
if char == '\\n':
break
passwordArray.append(char)
return passwordArray
print (username)
print (URL)
getting this error:
Problem invoking WLST - Traceback (innermost last):
(no code object) at line 0
File "/scratch/aime/work/stmp/wlstCommand.py", line 10
while 1:
^
SyntaxError: invalid syntax
Your indentation is not correct. Your while should be indented the same as the line above it.
Python uses indentation to "separate" stuff and the thing with that is you need to have the same kind of indentation across the file. Having a fixed kind of indentation in the code you write is good practice. You might want to consider a tab or four spaces(The later being the suggestion in the PEP8 style guide)
Python is sensitive and depended on indentation. If it complains "invalid Format", that is better than "invalid syntax".