2

I know this might sound silly, but I want to know if there is a way like this to use.

My code is:

print(a (+=) if a==1 else (-=) b)

What I want it to do is,

if a==1:
    print(a+b) 
else:
    print(a-b)
OneCricketeer
  • 126,858
  • 14
  • 92
  • 185

3 Answers3

4

Of course.

print(a+b if a==1 else a-b)

The word you're looking for is ternary operator.

Community
  • 1
  • 1
Jason
  • 2,170
  • 2
  • 15
  • 24
  • if amountPaid.group(1): shelfFile[str(name)+'balance']+=float(amountPaid.group(2)) else: shelfFile[str(name)+'balance']-=float(amountPaid.group(2)). This is the actual code, so if I do the above that would produce a large line. – Deepak Krishna Apr 06 '16 at 19:35
  • `shelfFile[str(name)+'balance']+=float(amountPaid.group(2)) if amountPaid.group(1) else shelfFile[str(name)+'balance']-=float(amountPaid.group(2))` :) – Jason Apr 06 '16 at 19:36
  • Is it possible to reduce the length of the code? – Deepak Krishna Apr 06 '16 at 19:40
  • if it is difficult to read of too long, using the ternary notation, you should use a traditional multiline if / else, to improve readability – DevLounge Apr 06 '16 at 19:42
  • In that case, it's better to put it on four lines for readability's sake. – Jason Apr 06 '16 at 19:43
  • Thanks, I should concentrate more on readability :) – Deepak Krishna Apr 06 '16 at 19:46
1

You can do this using the ternary condition operator:

a = a + b if a == 1 else a - b

If a == 1 is true, then a will hold the result of a + b, else it will hold the result of a - b

Demo:

a = 4
b = 2

# a should equal to 2
a = a + b if a == 1 else a - b

a = 1
b = 2

# a should equal to 3
a = a + b if a == 1 else a - b
idjaw
  • 21,992
  • 6
  • 53
  • 69
  • if amountPaid.group(1): shelfFile[str(name)+'balance']+=float(amountPaid.group(2)) else: shelfFile[str(name)+'balance']-=float(amountPaid.group(2)). This is the actual code, so if I do the above that would produce a large line. – Deepak Krishna Apr 06 '16 at 19:37
  • Thanks for the ideas :) – Deepak Krishna Apr 06 '16 at 19:47
  • @DeepakKrishna You are welcome. Don't forget to accept the answer that helped you as it indicates to other readers what you found helpful. – idjaw Apr 06 '16 at 19:47
0
a = a+b if a==1 else a-b

is the sane and reasonable person's approach, so here's the less sane version that more directly selects the operation, not the complete expression including operands, removing the need to repeat the operands in two places:

from operator import iadd, isub  # Like to += and -=, but you need to assign return

a = (iadd if a == 1 else isub)(a, b)

or even more concise/insane using bools to index a tuple:

a = (isub, iadd)[a == 1](a, b)

To be clear, this is silly. Just use a = a+b if a==1 else a-b.

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184