Search code examples
pythonsyntax-errorconditional-operator

SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? : python shorthand if-else


resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

prompt = input("What would you like? (espresso, latte or cappuccino):")
if prompt == 'report':
    for i in resources:
        k = 'g' if i == 'coffee' else k = 'ml'
        print(f'{i} : {resources[i]}')

Abovementioned code gives me error

"k = 'g' if i == 'coffee' else k = 'ml'
    ^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?"

but works when I used print statements instead of assignment statement like

print('g') if i == 'coffee' else print('ml')


Solution

  • You want:

    k = 'g' if i == 'coffee' else 'ml'
    

    That is to say, there's only one statement (the overall k = ...); everything on the right of = is an expression that evaluates to either 'g' or 'ml', so the k = can't and shouldn't be repeated.

    print('ml') is also an expression (albeit one that evaluates to None), so it works in that position; but k = 'ml' is only a statement and cannot be used in an expression-only context.