For some reason I can't remember how to do this - I believe there was a way to set a variable in Python, if a condition was true? What I mean is this:
value = 'Test' if 1 == 1
Where it would hopefully set value to 'Test' if the condition (1 == 1) is true. And with that, I was going to test for multiple conditions to set different variables, like this:
value = ('test' if 1 == 1, 'testtwo' if 2 == 2)
And so on for just a few conditions. Is this possible?
Yes, you can assign the value of variable inside if.
No. Assignment in Python is a statement, not an expression.
This is the closest thing to what you are looking for:
value = 'Test' if 1 == 1 else 'NoTest'
Otherwise, there isn't much else.
You can also do:
value = (1 == 1 and 'test') or (2 == 2 and 'testtwo') or 'nope!'
I prefer this way :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With