Python: For loop

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


Python For loop works like looping statement in other languages and iterates over array of objects. The syntax is quite similar to Java as you would see below:

Python For Loop Example

 
#!/usr/bin/python
 
for i in range(1, 5):
	print i
else:
	print 'End of python for loop'

Python For Loop similarity with Java Foreach

In Java, the syntax for foreach loop is:

for (type var : arr) {
    body-of-loop
}

Example of Java foreach loop is:

int[] ar = {1, 2, 3};
int sum = 0;
for (int d : ar) {  // d gets successively each value in ar.
    sum += d;
}

Python For Loop Using Enumerate

Here we use Python enumerate to run with Python for loop.

for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
    print i, season

Output of the code above is:

0 Spring
1 Summer
2 Fall
3 Winter





Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.