This question already has answers here:
Why do I get the syntax error "SyntaxError: invalid syntax" in a line with perfectly valid syntax?
(4 answers)
Closed 4 months ago.
I've recently been trying to code a program which plays domino with two players and with input, but apparently my syntax is flawed at the line where I define a function. I think it might be because of my near-zero experience with coding π
, but after I've searched on the internet, I haven't found any solution.
Here's the code :
def comptage():
occurences_of_numbers=[]
for i in range(7):
a=0
for k in range(7):
if i in list(hand[k]):
a=a+1
occurences_of_numbers.append(a)
return(occurences_of_numbers)
File "<string>", line 36
def comptage():
^
SyntaxError: invalid syntax
This function counts the numbers of occurrences of the numbers (0,1,2,3,4,5,6) in the tuples representing the dominos in the list named hand. I then use the function for other functions.
available_draws=14
opponent_hand=7
while comptage()[list(board[0])[0]]==0 and comptage()[list(board[len(board)-1])[1]]==0:
inpt_list=list(map(int,input(' Quel domino piochΓ© ?')))
M.append((inpt_list[0],inpt_list[1]))
available_draws=available_draws-1
#board is a tuple list representing the board
def riposte():
probability=[]
for i in range(7):
b=0
for k in range(len(board)):
if i in list(board[k]):
b=b+1
probability.append((7-comptage()[i]-b)/(28-len(hand)-len(board))*(opponent_hand/(opponent_hand+available_draws)))
return(probability)
This error popped up after I changed something in the riposte() function (I added the b characteristic). But it shows the mistake for the comptage() function. I don't know why it showed that.
I've tried changing the code a bit, rewriting it, and using other variants, but the error message stands still.
The rest of the code is : (some unfinished stuff)
zero=[]
one=[]
two=[]
three=[]
four=[]
five=[]
six=[]
all_the_dominos=[zero,one,two,three,four,five,six]
for i in range(7):
for k in range(7):
all_the_dominos[i].append((i,k))
hand=[]
for i in range(1,8):
input_list=list(map(int,input(' Domino '+str(i)+' ?')))
hand.append((input_list[0],input_list[1]))
print(hand)
for i in range(7):
for k in range(7):
if hand[i] in all_the_dominos[k]:
del all_the_dominos[k][all_the_dominos[k].index(hand[i])]
elif tuple(reversed(list(hand[i]))) in all_the_dominos[k]:
del all_the_dominos[k][all_the_dominos[k].index(tuple(reversed(list(hand[i]))))
board=[(6,1),(1,2),(2,6),(6,6)]
#example of a board
available_draws=14
opponent_hand=7
while input(' Pioche adverse ?')=='oui':
opponent_hand=opponent_hand+1
available_draws=available_draws-1
The only thing that comes after what is problematic is the last bit.
Help would be greatly appreciated. π
!! UPDATE !!
I've trisd another version of the compatge function, but it still shows the same error :
def comptage():
F=[0,0,0,0,0,0,0]
for i in range(7):
for k in range(len(M)):
if i in list(M[k]):
F[i]=F[i]+1
return(F)
But something's strange : i can't even define a variable !
a=0
File "<string>", line 34
a=0
^
SyntaxError: invalid syntax
I definitely think there is a problem with my phone because i've downloaded several other coding programs and always got the same error.
It's strange because it was working fine and all of a sudden, it doesn't allow me to do anything.
Well maybe there's just a problem with the code π but i really don't think so.
It looks like you have 1 more closing parenthesis ()) than opening parenthesis (() on this line: P.append((7-comptage()[i]-b)/(28-len(M)-len(J))*(aM/(aM+p)))
Actually, I've found the problem : there was just a missing bracket π. I'm new to Python so I didn't pay enough attention even though I thought I did.
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 in Python 3. I am a begginer so links to good sites will also be helpful. Anyway my goal is to find two duplicated numbers in a list and then find the number of elements between them. When I run my module it comes up as invalid syntax with no explanation. All it said was Invalid Syntax with nothing else. Any help is appreciated.
def pirate_list(thelist):
duplicate = set()
duplicate_add = duplicate.add
f = []
for i in thelist:
if i in duplicate or duplicate_add(i):
f.append(i)
print (f)
f.reverse()
print(f)
break
else:
f.append(i)
print ("fail")
pirate_list([6,1,0,2,1,6])
def count_list(f):
duplicate = set()
duplicate_add = duplicate.add
s = []
for x in f:
if x in duplicate or duplicate_add(x):
s.append(x)
print len(s)
break
else:
s.append(x)
count_list(f)
The text under each def statement should be indented.
The last line refers to countlist which is not defined, and f which is defined inside a different function.
The def statements are to be indented. countlist should be count_list, on the last line as Jonathon Clede said.
Make it a practice to learn to understand error messages. They are vital to debugging your code. Even though there was no real error message this time, be sure to do it other times. SyntaxError by itself is usually caused by a pesky error like this indentation one.
If it is python2 code, then the only error I find is the undefined variable f in the last line.
If it is python3 code, then you must change print len(s) to print(len(s)) as print is a function in python3 and not a separate statement keyword.
Thanks for all the help. It was a rookie mistake forgetting parentheses for the print len(s) and also bringing the f list outside the functions.
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'm having trouble with my function/class in Python 3.3.1
This is the code:
def snell(ang1=None, ang2=None, v1=None, v2=None, n1=None, n2=None):
try:
if ang1==None and n1==None:
ang1=math.degrees(math.asin((math.sin(ang2)*v1)/v2)
n1=(n2*v1)/v2
print("ang1 is equal to:", ang1, sep='\n')
print("n1 is equal to:", n1, sep='\n')
Sorry that the code is separated weirdly, I am very new to this. In any case, the syntax error I'm getting only says "invalid syntax" and highlights the variable n1 in the line n1=(n2*v1)/v2. I am wondering what the problem could be, as I see nothing wrong with that snippit of the code. This is part of a larger section of code, but the rest contains a multitude of elif's in the same format of this if statement. If any portion of this request is atrociously written please tell me how to improve it...much appreciated.
You're missing a closing ) on this line :
ang1=math.degrees(math.asin((math.sin(ang2)*v1)/v2))
I'm a beginner at python with experience in Java having to write a python module for a Virtual robot challenge for my high schools MESA(A technology based competition) club. I have been trying to solve this weird problem for days and I only have 6 hours left to fix all the bugs in my code! The "invalid syntax" always occurs on the first line after a while loop here is the relevant information:
Keep in mind that values have been properly added to the lists
Relevant code:
interestlengthl=list()
interestlengthr=list()
interestpoint=list()
def do_examine(robot):
examinecount=0;
while (examinecount<(max(interestpoint)) <-the while loop
i=2+2 <-a innocent line used as an example, this returned an invalid syntax
maxpoint=max(interestpoint)
tomove=(currentposition-(max[interestpoint]-interestpoint(examinecount)))
robot.step_forward(tomove)
leftscan=robot.sense_steps(robot.SENSOR_LEFT)
rightscan=robot.sense_steps(robot.SENSOR_RIGHT)
if (rightscan==interestlengthr(examinecount):
robot.turn_right()
do_rowscan(robot)
if (leftscan==interestlengthl(examinecount):
robot.turn_left()
do_rowscan(robot)
examinecount+=1
robot.turn_right(2)
currentposition=robot.sense_steps(robot.SENSOR_FORWARD)
robot.turn_right(2)
Relevant error:
File "L:\controllers\controller_zigzag.py", line 35
i=2+2
^
SyntaxError: invalid syntax
While loops should have a colon on them, such as with:
while examinecount < max (interestpoint):
just like your if statements further down. And, as an aside, it's not C - you don't need parentheses around the entire conditional.
The syntax error is that you must place a colon after the loop, AND you have unbalanced brackets: while (examinecount<(max(interestpoint)) -> while (examinecount<(max(interestpoint))):