Python Conditional Variable Setting

107,517

Solution 1

This is the closest thing to what you are looking for:

value = 'Test' if 1 == 1 else 'NoTest'

Otherwise, there isn't much else.

Solution 2

You can also do:

value = (1 == 1 and 'test') or (2 == 2 and 'testtwo') or 'nope!'

I prefer this way :D

Solution 3

Less obvious but nice looking term:

value = ('No Test', 'Test')[1 == 1]
print(value) # prints 'Test'
Share:
107,517

Related videos on Youtube

SolarLune
Author by

SolarLune

Updated on July 09, 2022

Comments

  • SolarLune
    SolarLune almost 2 years

    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?

  • SolarLune
    SolarLune over 12 years
    Ah, I was missing the 'else', and it didn't tell me I needed one. I guess I should've known better, since if the condition doesn't equate, it wouldn't be set to anything. Thanks!
  • James
    James over 12 years
    In case it isn't obvious, you can chain these (as in value = v1 if c1 else v2 if c2 else v3). An alternative is to use a dictionary.
  • Chris
    Chris over 4 years
    Let's please have it obvious. We code for humans. Not for machines. The machines can read anything that's not an error, alright. But humans cannot. And it's us that make the mistakes so we have to make it easier for us. :)
  • Ekrem Dinçel
    Ekrem Dinçel over 4 years
    It looks good, but this will not work as we want: value = (1 == 1 and '') or (2 == 2 and 'testtwo') or 'nope!'
  • rocksNwaves
    rocksNwaves about 4 years
    I actually like this a lot. It's quite understandable (and I happen to be a human). Thanks for sharing this extra tidbit. Cheers!
  • Borjovsky
    Borjovsky almost 3 years
    Tip: The use of 'else' is mandatory here. But if the variable already exists, and you don't want it to change if the condition is not satisfied, just make it equal to itself: value = 'Test' if 1 == 1 else value