Home »
Python
Behavior of increment and decrement operators in Python
By IncludeHelp Last updated : December 08, 2024
Python Increment and Decrement Operators
Python is considered to be a consistent and readable language. Unlike in Java, python does not support the increment (++) and decrement (--) operators, both in precedence and in return value.
Example
For example, in python the x++ and ++x or x-- or --x is not valid.
x=1
x++
Output
File "main.py", line 2
x++
^
SyntaxError: invalid syntax
Example
x=1
print(--x)
# 1
print(++x)
# 1
print(x--)
'''
File "/home/main.py", line 8
print(x--)
^
SyntaxError: invalid syntax
'''
Reason for the above errors
The reason for this is, in Python integers are immutable and hence cannot be changed.
Implementing Increment and Decrement Operators
To implement increase and decrement operators in Python, you have to use the compound assignment with + and - signs. Use += to increment the variable's value and -= to decrement the variable's value. Or, simply perform the arithmetic operations (x = x + 1 to increment and x = x - 1 to decrement).
Example
# Initialize a variable with 10
x = 10
# Incrementing the value
x += 1
print(x)
# Decrementing the value
x -= 1
print(x)
# Incrementing the value
x += 1
print(x)
# Incrementing the value
x += 1
print(x)
Output
11
10
11
12