Here is the example:
age = 10
reject = False
if age < 10:
st = 'Kid'
reject = True
else:
st='Adult'
reject = False
Is it possible? Something like:
statement1:statement2 if age < 10 else statement3:statment4
I am still having problems with understanding ternary operator in Python.
wim
368k114 gold badges682 silver badges819 bronze badges
3 Answers 3
Assignment statements support multiple targets:
>>> age = 10
>>> st, reject = ('Kid', True) if age < 10 else ('Adult', False)
>>> st, reject
('Adult', False)
answered Jun 1, 2017 at 21:46
wim
368k114 gold badges682 silver badges819 bronze badges
Sign up to request clarification or add additional context in comments.
You could do it like this:
st, reject = ('Kid', True) if age < 10 else ('Adult', False)
answered Jun 1, 2017 at 21:48
rammelmueller
1,1181 gold badge14 silver badges30 bronze badges
2 Comments
metazord
is there another possible way??? assuming that if kid < 20, if less than 20 ONLY assign "rejected=True" and for adult st="Adult" and Rejected=False
rammelmueller
other than st, reject = (None, True) if age < 20 else ('Adult', False) i can't think of anything off the top of my head
You can use:
st, reject = ('Kid', True) if age < 10 else ('Adult', False)
When you use:
var1, var2 = 1, 2
You are doing the same as:
var1 = 1
var2 = 2
And when you use:
var1 = 1 if x == y else 2
Your are doing the same as:
if x == y:
var1 = 1
else:
var1 = 2
If you want with this define multiples variables you have to make a tuple () with the variables and they will be unpacked.
answered Jun 1, 2017 at 22:14
Ender Look
2,4212 gold badges19 silver badges41 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-py
true-expression if condition else false-expression.globals().__setitem__('st', 'Kid'), for example.