I have the following code
num1 = 10
someBoolValue = True
I need to set the value of num1
to 20
if someBoolV
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
>>>
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)
You can definitely use num1 = (20 if someBoolValue else num1) if you want.
Another way
num1 = (20*boolVar)+(num1*(not boolVar))
Use this:
num1 = 20 if someBoolValue else num1
num1 = 20 * someBoolValue or num1