Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

I get a syntax error and an error saying illegal target for variable annotation. How do I fix it? [closed]

Writer Matthew Barrera

Here I am trying to compare items from two lists and give a score based on who has the higher no at the given index. But I always shows syntax error in the first elif and says illegal target for variable annotation.

def comparetriplets(a, b): p = 0 q = 0 x = 0 while x < 3: if a[x] > b[x]: p = 1 q = 0 x += 1 elif b[x] > a[x]: p = p+0 q = q+1 x += 1 elif a[x] == b[x]: p = p+0 q = q+0 x += 1
return [p, q] 

elif b[x] > a[x]: SyntaxError: invalid syntax

2

2 Answers

I have just concluded a long and fruitless search for the meaning of "illegal target for variable notation". But have come to the realization that the error message was trying to tell me that I had broken a sequence of 'if' and 'elif' statements, just as with the questioner's original code. I had placed a temporary, unindented print statement after my initial 'if', which exited me from what should have been an 'if', 'elif' sequence. The error message flagged the otherwise functional 'elif' statement, but the real problem was with the indentation of the earlier print statement.

Do you mean to write x += 1 statement inside if block and elif block like below:

def comparetriplets(a, b): p = 0 q = 0 x = 0 while x < 3: if a[x] > b[x]: print('Begining of if :' , x) p = 1 q = 0 x += 1 print('End of if :', x) elif b[x] > a[x]: print('Begining of elif-1 :' , x) p = p+0 q = q+1 x += 1 print('End of elif-1 : ', x) elif a[x] == b[x]: print('Begining of elif-2 : ' , x) p = p+0 q = q+0 x += 1 print('End of elif-2 : ', x) return [p, q] 

Please let me know if it clarifies your doubt or solves the syntax error.

Calling the function comparetriplets:

import numpy
import random
a = random.sample(range(1,51),4) # Generate a list of four random numbers
b = random.sample(range(1,51),4)
print(a)
print(b)
p,q = comparetriplets(a, b)

Output:

a : [32, 3, 27, 21]
b : [20, 8, 35, 37]
Begining of if : 0
End of if : 1
Begining of elif-1 : 1
End of elif-1 : 2
Begining of elif-1 : 2
End of elif-1 : 3
6