r/pythonhelp • • Dec 23 '22

if else in one line syntax

My question is how exacly is the syntax on something like:

color = ("white" if val == "1" elif val == "2" "black")

Basically this, but in one line:

if val == "1":

color = "white"

elif val == "2":

color = "black"

Thanks in advance

2 Upvotes

4 comments sorted by

1

u/bulaybil Dec 23 '22

One-liners are more of a Perl thing. In Python, we would use a dictionary here.

1

u/carcigenicate Dec 24 '22

You'd need two separate conditional expressions; one after the other. There is not elif with conditional expressions.

1

u/Goobyalus Dec 24 '22

You could chain conditional expressions:

"a" if val == 1 else "b" if val ==  2 else None

Don't, though.


You could also create and index a dict in one line:

{1: "a", 2: "b"}[key]

Also probably don't, though.


1

u/AmongstYou666 Dec 24 '22 edited Dec 24 '22

color = ["", "white", "black"][val]