for loop in c++ and python
Solution 1
I'd in general advice against modifying the iteration variable in C++, as it makes the code hard to follow.
In python, if you know beforehand which values you want to iterate through (and there is not too many of them!) you can just build a list of those.
for i in [0,1,4]:
print i
Of course, if you really must change the iteration variable in Python you can just use a while loop instead.
i = 0
while i < 5:
if i==2:
i=i+2
print i
i = i + 1
Solution 2
i
is reset each iteration, meaning any mutation to i is ignored the next loop around. As Daniel Fischer said in a comment, if you want to do this in Python, use a while loop.
It's like:
for (int i = 0; i < 5; ++i) {
int x = i;
if (x == 2) {
x = x + 2;
}
std::cout << x << std::endl;
}
Solution 3
The i
variable is being set at every iteration of the loop to the output of the range(5)
iterator. Although you can modify in the loop, it gets overwritten.
Related videos on Youtube
Comments
-
g4ur4v almost 2 years
I am very new to python.I had a small query about for loop in c++ and python.In c,c++ if we modify the variable
i
as shown in below example ,that new value ofi
reflects in the next iteration but this is not the case in for loop in python.So ,how to deal with it in python when it is really required to skip some iterations without actually using functions likecontinue
,etc.for loop in c++
for(int i=0;i<5;++i) { if(i==2) i=i+2; cout<<i<<endl; }
Output
0 1 4
for loop in python
for i in range(5): if i==2: i=i+2 print i
Output
0 1 4 3 4
-
Daniel Fischer about 11 yearsIn Python, use
while
to do such things.
-