Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for loop question

I was wondering how to achieve the following in python:

for( int i = 0; cond...; i++)   if cond...     i++; //to skip an run-through 

I tried this with no luck.

for i in range(whatever):   if cond... :     i += 1 
like image 383
Joe Dunk Avatar asked Mar 12 '10 00:03

Joe Dunk


People also ask

What is for loop in Python interview questions?

A “for” loop is the most preferred control flow statement to be used in a Python program. It is best to use when you know the total no. of iterations required for execution. It has a clearer and simple syntax and can help you iterate through different types of sequences.

What is for loop in Python example?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.


2 Answers

Python's for loops are different. i gets reassigned to the next value every time through the loop.

The following will do what you want, because it is taking the literal version of what C++ is doing:

i = 0 while i < some_value:     if cond...:         i+=1     ...code...     i+=1 

Here's why:

in C++, the following code segments are equivalent:

for(..a..; ..b..; ..c..) {     ...code... } 

and

..a.. while(..b..) {      ..code..      ..c.. } 

whereas the python for loop looks something like:

for x in ..a..:     ..code.. 

turns into

my_iter = iter(..a..) while (my_iter is not empty):     x = my_iter.next()     ..code.. 
like image 186
jakebman Avatar answered Oct 05 '22 15:10

jakebman


There is a continue keyword which skips the current iteration and advances to the next one (and a break keyword which skips all loop iterations and exits the loop):

for i in range(10):     if i % 2 == 0:       # skip even numbers       continue      print i 
like image 34
tux21b Avatar answered Oct 05 '22 16:10

tux21b