Multiple elif statements show invalid syntax | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

11th Feb 2017, 3:57 PM
Carlos Hidalgo
Carlos Hidalgo - avatar
4 Answers
+ 6
Yes, invalid syntax means you perhaps forgot to close a quotation, bracket or parenthesis. Try it on CodePlayground and see what happens ;)
11th Feb 2017, 7:41 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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.
12th Feb 2017, 9:32 AM
Aidan Haddon-Wright
Aidan Haddon-Wright - avatar
+ 1
Your if-else tree seems to be okay. If you're getting an error, it is probably the line before the elif statement.
11th Feb 2017, 4:10 PM
Mike L.
Mike L. - avatar
0
Thank you, problem solved :)
12th Feb 2017, 2:20 PM
Carlos Hidalgo
Carlos Hidalgo - avatar