I don't understand how python deals with variables with same names in a program, especially in for
loops.
The following is a python program
for i in range(10):
if i%2!=0:
print i
continue
i += 2
print i
The outcome is as follows
2
1
4
3
6
5
8
7
10
9
I don't understand why I get the above-mentioned outcome. In my opinion, when i
is 0, the program will execute i+=2
, so i
becomes 2, and is printed out. Then the for
finishes one loop so that i
is increased by 1. So after the first loop, i
should become 3. I test my opinion using the following C++ program, the result is exactly what I expect.
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int i;
for (i = 0; i < 10; ++i)
{
if(i%2!=0){
cout << i << endl;
continue;
}
i += 2;
cout << i << endl;
}
return 0;
}
The outcome is as follows:
2
3
6
7
10
Why is the result of python program looks like that?
To further exploit the reasons, I add more print
sentences to the python program as follows:
for i in range(10):
print 'round ', i
if i%2!=0:
print 'in if, i = ',i
continue
print 'before i+=2, i is ',i
i += 2
print 'after i+=2, i is ',i
Then the outcome becomes:
round 0
before i+=2, i is 0
after i+=2, i is 2
round 1
in if, i = 1
round 2
before i+=2, i is 2
after i+=2, i is 4
round 3
in if, i = 3
round 4
before i+=2, i is 4
after i+=2, i is 6
round 5
in if, i = 5
round 6
before i+=2, i is 6
after i+=2, i is 8
round 7
in if, i = 7
round 8
before i+=2, i is 8
after i+=2, i is 10
round 9
in if, i = 9
It seems python treat i
's differently in different parts of the program. It implicitly declares another variable named i
. But why? And what is the rule of python to decide whether to declare a new variable implicitly?