1

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
  • Do you want to add bills[1] + 1 to bills[2] in the else part? Commented Jan 9, 2017 at 13:36

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

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.