List comprehension if-else in one line
I'm shortening a code and trying to compress an if/else statement but I don't how to. This is what I have If opcn1 == 1: var1 = X Elif opcn1 == 2: Var1 = Y Elif opcn1 == 3: Var1 = Z Elif opcn1 == n... etc...
You can try this :)) var1 = X if opcn1 == 1 else Y if opcn1 == 2 else Z if opcn1 == 3 else .... Example : x = 1 y = 'one' if x == 1 else 'two' if x == 2 else 'idk' print(y) # one
That isn't a list comprehension but TERNARY operator. print (something if something else nothing )
You can use a tuple: Var1 = (None, X, Y, Z)[opcn1] https://code.sololearn.com/cKcgEYDfJ5Wi/?ref=app
How to read this?
Class and instance attributes
How does this works?
Button after Button