Python Ternary Operator adding integers

752 views Asked by At

I am trying to do a ternary operation in python by adding 1 to an item in an array if money == 100 and adding 1 to another item if it does not. But I keep on getting an invalid syntax error.

 bills[2] += 1 if money == 100 else bills[1] += 1
                                             ^
SyntaxError: invalid syntax

Here is the code.

def tickets(people):
change =0 
bills = [0,0,0]
for i,money in enumerate(people):
    if money == 25:
        change += 25
        bills[0] += 1
        str = "This is the %d th person with %d money" % (i,money)
        print(str)

    else:
        bills[2] += 1 if money == 100 else bills[1] += 1
        change -= (money -25)
        str = "This is the %d th person with %d money" % (i,money)
        print(str)
        print("change is %d" % change)

if change < 0:
    return "NO"
else:
    return "YES"
1

There are 1 answers

0
Martijn Pieters On

You can't put statements inside expressions. += (assignment) is a statement. You can only use expressions inside specific parts of a statement (like the right-hand-side of an assignment).

You can use a conditional expression here, but use it to pick what index to assign to:

bills[2 if money == 100 else 1] += 1

This works because the part inside a [...] subscription in an assignment target also takes an expression.