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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s