Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop in c++ and python

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 of i 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 like continue ,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
like image 786
g4ur4v Avatar asked Jun 11 '26 13:06

g4ur4v


1 Answers

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
like image 147
OnePie Avatar answered Jun 14 '26 03:06

OnePie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!