2

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.

3
  • The syntax you requested is not possible. The conditional expression syntax is true-expression if condition else false-expression. Commented Jun 1, 2017 at 21:55
  • @TerryJanReedy Well, you can actually bind names with expressions. globals().__setitem__('st', 'Kid'), for example. Commented Jun 1, 2017 at 22:03
  • Just use the if-else statement. There is no good reason to try to cram your code into a single line, especially if it requires weird, unidiomatic usage of language constructs not meant to achieve that. Commented Jun 1, 2017 at 22:17

3 Answers 3

7

Assignment statements support multiple targets:

>>> age = 10
>>> st, reject = ('Kid', True) if age < 10 else ('Adult', False)
>>> st, reject
('Adult', False)
Sign up to request clarification or add additional context in comments.

2 Comments

is there another possible way??? assuming that if kid < 20, if less than 20 ONLY assign "rejected=True" and for adult assign st="Adult" and Rejected=False
Technically possible, but ugly. Just use an if statement and stop trying to be so fancy.
5

You could do it like this:

st, reject = ('Kid', True) if age < 10 else ('Adult', False)

2 Comments

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
other than st, reject = (None, True) if age < 20 else ('Adult', False) i can't think of anything off the top of my head
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.