Python
If you are familiar with other programming languages like C, Java, PHP then you know there exists two operators namely Increment and Decrement operators denoted by ++
and --
respectively.
There is no Increment and Decrement operators in Python.
This may look odd but in Python if we want to increment value of a variable by 1 we write +=
or x = x + 1
and to decrement the value by 1 we use -=
or do x = x - 1
.
Some of the possible logical reasons for not having increment and decrement operators in Python are listed below.
+=
and -=
.++
and --
will result in the addition of some more opcode to the language which may result into slower VM engine.++
and --
is in loop and in Python for
loop is generally written as for i in range(0, 10)
thus removing the need for a ++
operator.There are other reasons as well and you can Google them.
Following is a simple PHP code using for loop to print from 1 to 10.
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i . " ";
}
?>
The above code will print integer numbers from 1 to 10.
We can achieve the same result in Python using for loop.
for i in range(1, 11):
print(i)
The above Python code will also print integer numbers from 1 to 10.
We will cover Python For Loop in the loop tutorials. And we will also talk more about the range()
function.
In the following C code we are printing integer numbers from 10 to 1 using for loop.
#include <stdio.h>
int main() {
int i;
for (i = 10; i >= 1; i--) {
printf("%d ", i);
}
return 0;
}
We can achieve the same result in Python by writing the following code.
for i in range(10, 0, -1):
print(i)
ADVERTISEMENT