89DEVs

How to decrement in Python?

How to decrement in Python?

To decrement in Python, use the - or -= operator. Both ways are useably and correct, however the -= is more precise and therefore more pythonic. Programming languages like PHP or C use the -- operator to decrement numbers as shown below. Python does not offer this possability. $a = 5; $a++; // a is now 6

Decrement using - operator

To decrement a number, use the - operator as shown below. # decrement using - operator # define variable x and set value to 2 x = 2 # decrement variable x by 1 x = x - 1 # print the new value of variable x print(x) In this quick example, the variable x is defined and its value is set to 2. Then variable x is decremented by 1. Finally, the new value of variable x is printed. 1

Decrement using -= operator

To decrement a number in Python, use the -= operator as shown below. This way is considered the more pythonic way, because it is more concise. # decrement using -= operator # define variable x and set value to 2 x = 2 # decrement variable x by 1 using the -= operator x -= 1 # print the new value of variable x print(x) First the variable x is defined and its value is set to 2. Then the variable is incremented by 1. Finally, the new value of variable x is printed. 1

decrement in loops

To decrement in a loop, use the -= operator as shown below. It is possible to use the - operator in the same way. # decrement number in loops myList = [5, 4, 3, 2, 1] for number in myList: number -= 1 print(number) In this example, all elements of myList are decrement by 1 using the -= operator. Then each element is printed. 4 3 2 1 0

decrement characters

The decrement operator is also useful to find the last character in the list of ascii characters. For example: If we decrement the character b, the character a is returned. # decrement characters # find integer representation of the character character = ord('b') # decrease integer representation by one character -= 1 # convert integer representation back to actual character character = chr(character) # print the character print(character) First, the character is converted into the integer representation of the actual character. Then, the integer representation is decremented by 1. Then, the integer representation is converted back into the actual character. Finally, the character is printed. The previous character of b in the ascii list is a. a

Is there a -- operator in Python?

It is not possible to decrement numbers in Python with the -- operator like in other programming languages for example Java or PHP. In case the -- operator is still used in Python, a SyntaxError exception is raised as shown below. SyntaxError: invalid syntax

                
        

Summary


Click to jump to section