HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Perl & Python: “for” Loop Example

Advertise Here For Profit

Xah Lee, 2005-01-15

Python

This is a example of “for” statement..

a = range(1,51) # creates a list
for x in a:
     if x % 2 == 0:
        print x, 'even'

In the above, the percent “%” symbol calculates the remainder of division. The range(m,n) function gives a list from m to n-1

Note that in this example, “for” goes over a list. Each time making “x” the value of the element.

Python also supports “break” and “continue” to exit the loop. “break” will exit the loop. “continue” will skip code and start the next iteration.

Here's a example of using “break”.

# python
for x in range(1,9):
     print 'yay:', x
     if x == 5:
          break

Perl

This is similar code in Perl.

@a=(1..50); # creates a list
for $x (@a) {
     if ( $x%2 ==0){
     print $x, " even\n";
}}

In this example, the (m..n) creates a list from m to n, including m and n.

Note: Perl also supports loop controls “next”, “last”, “goto” and few others. .

blog comments powered by Disqus