C style For loop in Python

A for loop in C/C++/PHP/Java Or many well-known programming language will appear as:

int loopStartVariable = 0;
int loopEndVariable = 5;
for(i=loopStartVariable; i < loopEndVariable; i++){
	// do something with i

Python has no C-style for loop, which is has is for in loop like foreach loop available in PHP.

To achive the same goal as the code snippet written in C above, we may write following code in python:

loopStartVariable = 0;
loopEndVariable = 5;
for i in range(loopStartVariable, loopEndVariable):
	# Do something with i
print "loop ends here"

2 thoughts on “C style For loop in Python

  1. You just showed how the python for worked with ranges.
    Actually, c-style “for” loops are much more generic. Their shape is :
    for( initialisation statement ; end test ; post-iteration satement)
    Which allows complex things like :
    for (i=1,j=2 ; (i+j)%17 != 0 ; i=j+2i, j=3j-i)

    That’s what people are looking for when they ask about c-style for loops.

Comments are closed.