Python3中一步实现变量自增赋值?为何a++语法报错?
z = a++ throw a SyntaxError in Python, and how to achieve increment like ++? Hey there! Let's unpack your problem clearly.
Why you're getting that SyntaxError
Unlike languages like C, Java, or JavaScript, Python doesn't have the ++ (or --) operator at all. This is a deliberate design choice—Python prioritizes readability and avoids ambiguous syntax. The ++ operator in other languages has two distinct behaviors (prefix: increment first then use the value; suffix: use the value first then increment), which can lead to confusion. Python opted to skip this entirely, so writing z = a++ is just invalid syntax to the interpreter.
Your original working code already does exactly what you want in a clear, Pythonic way:
a = 90 z = a + 1 print(z) # Outputs 91
How to mimic the ++ behavior in Python
If you're looking to replicate the two common behaviors of ++ from other languages, here's how to do it properly in Python:
1. Suffix ++ (use the original value first, then increment a)
This is what you might have thought z = a++ would do—assign a's current value to z, then increase a by 1:
a = 90 z = a # Assign original value to z a += 1 # Increment a by 1 print(z) # Outputs 90 print(a) # Now a is 91
2. Prefix ++ (increment a first, then use the new value)
If you want to increment a first and then assign the updated value to z:
a = 90 a += 1 # Increment a first z = a # Assign the new value to z print(z) # Outputs 91
3. Just increment a (no assignment to another variable)
If you only need to increase a by 1 (like a++ on its own), use Python's augmented assignment—it's the closest equivalent:
a = 90 a += 1 # Same effect as a = a + 1, but cleaner print(a) # Outputs 91
内容的提问来源于stack exchange,提问作者m.d venkatesh

