Monday 20 September 2021

Python do not have ++ (incremental), -- (decremental) operators

At the time of writing this post, Python do not have incremental and decremental operators. If you are from Java kind of language background, you may be surprised with this. But there are multiple ways to achieve this behavior.

 

Using Compound assignment

a += 1, it is same as incrementing a by 1.

a -= 1, it is same as decrementing a by 1.

 

augument_operators_1.py

a = 10
print("a = ", a)

a += 1
print("a = ", a)

a -= 1
print("a = ", a)

 

Output

a =  10
a =  11

 

Using range function while iterating

 

Example 1: Iterate from 0 to some maximum number.

for (i = 0; i < 6; i++){
	System.out.println(i)
}

 

Above snippet can be written like below.

for i in range(6):
    print(i)

Example 2: Iterate from some number to other number

for (i = 2; i < 6; i++){
	System.out.println(i)
}


Above snippet can be written like below.

for i in range(2, 6):
    print(i)


Example 3: Change the step size to 3.

for (i = 2; i < 6; i+=3){
	System.out.println(i)
}


Above snippet can be written like below.

for i in range(2, 6, 3):
    print(i)


Example 4: Decrementing the step size.

for (i = 6; i > 2; i--){
	System.out.println(i)
}


Above snippet can be written like below.

for i in range(6, 2, -1):
    print(i)


range_function_1.py

print("Iterate from 0 to some maximum number")
for i in range(6):
    print(i)

print("\nIterate from some number to other number")
for i in range(2, 6):
    print(i)

print("\nChange the step size to 3")
for i in range(2, 6, 3):
    print(i)

print("\nDecrementing the step size")
for i in range(6, 2, -1):
    print(i)


Output

Iterate from 0 to some maximum number
0
1
2
3
4
5

Iterate from some number to other number
2
3
4
5

Change the step size
2
5

Decrementing the step size
6
5
4
3


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment