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 = 1ifx== 'dog'else2ifx== 'cat'else0if x.isspace() else None

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

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

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

Demo:

>>>x = 'cat'>>>1if x == 'dog'else2if x == 'cat'else0if x.isspace() elseNone
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?"