0
Multiple elif statements show invalid syntax
I have some code with like 10 elif statements, and when I try to run it, it marks invalid syntax in the 6th statement, but I already checked it and it seems correct. Its like: if x == 1: some code elif x ==2: some code elif x ==3: some code elif x ==4: some code elif x ==5: some code elif x ==6: some code elif x ==7: <---Invalid Syntax some code elif x ==8: some code elif x ==9: some code elif x ==10: some code elif x ==11: some code else: print(error)
4 Respuestas
+ 6
Yes, invalid syntax means you perhaps forgot to close a quotation, bracket or parenthesis. Try it on CodePlayground and see what happens ;)
+ 4
I agree with @Mike L. however, instead of using a huge if-elif statement to test a bunch values, I would suggest using a dictionary. Dictionaries are powerful objects in python and you can use them in various ways. In this case, we can use them as a switch
def checkX(x):
d={0:"arg0", 1:"arg1", 2:"arg2"}
return d[x]
print(checkX(2))
#output: arg2
you can even store references to functions in dictionaries:
def func(n)
return n*2
d={0:func,1:func,2:func}
def checkX(x):
return d[x](x)
print(checkX(1))
#output: 2
I use this method all the time for event handling where you need to test for loads of different cases.
+ 1
Your if-else tree seems to be okay. If you're getting an error, it is probably the line before the elif statement.
0
Thank you, problem solved :)