Can't assign to literal error

Can you tell me what is wrong here?
image
Outside the function it’s no error and inside the function I receive this error.

Attached also the code in case the picture is not available for everyone:
‘’’
a = 5
print(a)

def main():
{
a = 5;
print(a);
}

main()
‘’’

Python does not use curly braces for code blocks, only for dictionaries. Also Python does not use semicolons to end statements.

If you write your code like this it should be fine:

a = 5
print(a)

def main():
    a = 6

main()
print(a)
1 Like

Python also uses {} for sets. At top level in 3.12.0a6, one gets

>>> {a=5}
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Both suggestions are legal.

Why does Python suggest here only ‘==’ and ‘:=’ when also ‘:’ would be legal (and perhaps more likely)?

Because we have a time machine, not a mindreading device. Python offers the most likely suggestions, not the ones that happen - for you - to be correct.

‘==’ and ‘:=’ most likely? Do you really believe that yourself?

indeed,now it works…thank you for your answer…I’m a newbie in python

1 Like

I’m not sure how the parser works, but at the point the error is detected, it definitely knows that it is parsing an expression (in which either == or := can appear). It’s less clear that it knows (without searching up some stack) that it is buried in middle of parsing a dict display, which is the only enclosing “scope” in which it would make sense to recommend a :.

@pablogsal Is there any possibility that the syntax error hinter could add ‘:’ to the hints in

>>> {a=5}
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

or would that require too much context?

It might be worth splitting this sub-topic off into its own thread :slight_smile: