Home » Python

Behavior of increment and decrement operators in Python

Python increment/decrement operators: Here, we are going to learn about the behavior of increment and decrement operators in Python.
Submitted by Sapna Deraje Radhakrishna, on January 19, 2020

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.

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
x=1

print(--x)
# 1
print(++x)
# 1

print(x--)
'''
  File "main.py", line 8
    print(x--)
             ^
SyntaxError: invalid syntax
'''

The reason for this is, in python integers are immutable and hence cannot be changed. So, we will have to do the following for incrementing,

x = 1

x=x+1
print(x)

x=x-1
print(x)

x +=2
print(x)

x -= 1
print(x)

Output

2
1
3
2





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.