Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 702
SolarLune Avatar asked Nov 14 '11 00:11

SolarLune


People also ask

Can you assign a variable to an IF statement?

Yes, you can assign the value of variable inside if.

Can we use assignment operator in if condition in Python?

No. Assignment in Python is a statement, not an expression.


2 Answers

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

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

Otherwise, there isn't much else.

like image 109
Donald Miner Avatar answered Sep 19 '22 15:09

Donald Miner


You can also do:

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

I prefer this way :D

like image 42
Mauro D'Agostino Avatar answered Sep 18 '22 15:09

Mauro D'Agostino