SolarLune
SolarLune

Reputation: 725

Python Conditional Variable Setting

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?

Upvotes: 61

Views: 160931

Answers (6)

Jaana Matokangas
Jaana Matokangas

Reputation: 1

(value:='Test') if 1==1 else ()

Upvotes: 0

Balaram Pradhan
Balaram Pradhan

Reputation: 1

Multiple if conditions can be used to assign value like switch case:

>>> inp=2
>>> res='two' if inp==2 else 'one' if inp==1 else 'three' if inp==3 else 'invalid'
>>> res
>>> two

Upvotes: 0

Serhii Aksiutin
Serhii Aksiutin

Reputation: 637

Less obvious but nice looking term:

value = ('No Test', 'Test')[1 == 1]
print(value) # prints 'Test'

Upvotes: 4

Pinja Jäkkö
Pinja Jäkkö

Reputation: 33

value = [1, 2][1 == 1] ;)

...well I guess this would work too: value = ['none true', 'one true', 'both true'][(1 == 1) + (2 == 2)]

Not exactly good programming practice or readable code but amusing and compact, at the very least. Python treats booleans as numbers, so True is 1 and False is 0. [1, 2][True] = 2, [1, 2][False] = 1 and [1, 2, 3][True + True] = 3

Upvotes: 1

Mauro D'Agostino
Mauro D'Agostino

Reputation: 101

You can also do:

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

I prefer this way :D

Upvotes: 8

Donald Miner
Donald Miner

Reputation: 39893

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

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

Otherwise, there isn't much else.

Upvotes: 125

Related Questions