Skip to content Skip to sidebar Skip to footer

Possible To Set Variable With Multiple If Statments?

I can do this: x ='dog' testvar = 1 if x == 'dog' else 0 My x in this case can be one of three things. 'dog', 'cat, or '' (empty) I would like to set testvar equal to 1 if x ==

Solution 1:

You can chain the if statements:

testvar = 1 if x == 'dog' else 2 if x == 'cat' else 0 if x.isspace() else None

You do need that last else statement though. Python sees this basically as:

testvar = 1 if x == 'dog' else (2 if x == 'cat' else (0 if x.isspace() else None))

with each nested conditional expression filling the else clause of the parent expression.

Demo:

>>> x = 'cat'
>>> 1 if x == 'dog' else 2 if x == 'cat' else 0 if x.isspace() else None
2

Another, more readable option is to use a mapping:

testmapping = {'dog': 1, 'cat': 2, ' ': 0}
testvar = testmapping.get(x)

Demo:

>>> testmapping = {'dog': 1, 'cat': 2, ' ': 0}
>>> testmapping[x]
2

Post a Comment for "Possible To Set Variable With Multiple If Statments?"