ChatGPT解决这个技术问题 Extra ChatGPT

One line if-condition-assignment

I have the following code

num1 = 10
someBoolValue = True

I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that

num1 = 20 if someBoolValue else num1

Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to

if someBoolValue:
    num1 = 20

I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass. All I got was syntax error. Nor I could just omit the ...else num1 part.

Just change it all to num1 = 20 if someBoolValue else 10. Then you save the num1=10 line as well?
Thanks. But this is not exactly my code. I meant that num1 exists already...

v
vidstige

I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:

num1 = 20 if someBoolValue else num1

If you exclude else num1, you'll receive a syntax error since I'm quite sure that the assignment must actually return something.

As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:

if someBoolValue: num1=20

I'm not a big fan of the num1 = someBoolValue and 20 or num1 for the exact same reason. I have to actually think twice on what that line is doing.

The best way to actually achieve what you want to do is the original version:

if someBoolValue:
    num1 = 20

The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.

Also, as a side note, num1 = 20 if someBoolValue is valid Ruby code, because Ruby works a bit differently.


Per PEP-308 (docs.python.org/2.5/whatsnew/pep-308.html), the conditional expression can be made clearer if put in paren, as in num1 = (20 if someBoolValue else num1).
Watch out for divide by-zero statements though -- num_cats = math.ceil(num_humans / my_var) if my_var > 1 else 1 generates divide by zero if my_var is 0, even though the conditional for that code is false
g
gigimon

Use this:

num1 = 20 if someBoolValue else num1

this is what i have been using .. and looking for an alternate.. thanks anyways!!
How to call this block ? I mean what is it name ?
it is a ternary operator
One should not use this approach if looping through large data sets since it introduces an unnecessary assignment in case we end up in the else-statement.
D
Debilski

In one line:

if someBoolValue: num1 = 20

But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.

if someBoolValue:
    num1 = 20

(Equally, camel caps should be avoided. So rather use some_bool_value.)

Note that an in-line expression some_value if predicate without an else part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.


Because it gets hard to read and you'll probably end up getting confused by your own code, and that's never a good idea.
@bdhar, why do you want to put it on one line? It won't run any faster, it will just be harder for other people to read
@gnibbler, no reason, actually. i was looking for a shorter form with better readability..
t
the Tin Man

you can use one of the following:

(falseVal, trueVal)[TEST]

TEST and trueVal or falseVal

Nice one liner conditional assignment
How is that "structure" called? I've never seen that in ~6 months of learning Python.
At least these are not assignments, unless you put one in front of them, and second, they will not work the way described here. The first one creates a tuple, then picks one of its elements by index. It will only work for tests that return an integer between -1 and 1, or True/False, since bool is a subclass of int. In all cases where the test returns something that would just evaluate true, it fails with an exception. Second one only works as long as trueVal doesn't evaluate false itself, which would result in falseVal beeing assigned even if the test was true.
it is nicely short, but also very tricky to safely be used as "recommended pattern", see above comment from Bachsau ... (so I downvoted it)
b
bad_coder

For the future time traveler from Google, here is a new way (available from Python 3.8 onward):

b = 1
if a := b:
    # this section is only reached if b is not 0 or false.
    # Also, a is set to b
    print(a, b)

Thank you for the answer, I was wondering what is this weird syntax and why it doesn't work with python3.7 :D
Note that this only available in Python>=3.8
the best clarification about the new if-else code style. thanks
V
Vahid Hallaji

If one line code is definitely going to happen for you, Python 3.8 introduces assignment expressions affectionately known as “the walrus operator”.

:=

someBoolValue and (num := 20)

The 20 will be assigned to num if the first boolean expression is True. The assignment must be inside parentheses here otherwise you will get a syntax error.

num = 10
someBoolValue = True

someBoolValue and (num := 20)
print(num) # 20

num = 10
someBoolValue = False

someBoolValue and (num := 20)
print(num) # 10

t
the Tin Man

No. I guess you were hoping that something like num1 = 20 if someBoolValue would work, but it doesn't. I think the best way is with the if statement as you have written it:

if someBoolValue:
    num1 = 20

M
Mike from PSG
num1 = 10 + 10*(someBoolValue is True)

That's my new final answer. Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good. Here's the prior answer... still good if you want add one thing for True cond and another for False:

num1 = 10 + (0,10)[someBoolValue is True]

You mentioned num1 would already have a value that should be left alone. I assumed num1 = 10 since that's the first statement of the post, so the operation to get to 20 is to add 10.

num1 = 10
someBoolValue = True

num1 = 10 + (0,10)[someBoolValue is True]

print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')

produced this output

num1 = 20
someBoolValue = True

Now I'm thinking that I should have answered 'num1 = 10 + 10*(someBoolValue == True)' Problem defined as the 'False' condition as a no-op basically. If it needed to be a choice of adding a different value for 'False' then the prior answer is a better fit. Do I edit my post or do this in the comments?
A
Ajean

If you wish to invoke a method if some boolean is true, you can put else None to terminate the trinary.

>>> a=1
>>> print(a) if a==1 else None
1
>>> print(a) if a==2 else None
>>> a=2
>>> print(a) if a==2 else None
2
>>> print(a) if a==1 else None
>>>

p
pacholik
num1 = 20 * someBoolValue or num1

j
j raj

Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.

Code:

num2 =20 if someBoolValue else num1
num1=num2

Y
Yaonan Qian

You can definitely use num1 = (20 if someBoolValue else num1) if you want.


Duplicate of answer(s) above?
R
Rody From Argentina

Another way num1 = (20*boolVar)+(num1*(not boolVar))


A
Ayesh Weerasinghe

You can do it this way.

try:
    a = [i for i in [20] if False][0]
except IndexError:
    print("Do what ever you want here")

You can solve your problem this way but, using 'try/except block' is not the best practice for python.