If you enjoyed this site, please consider donating $3. Any amount is appreciated. Thanks!

Perl-Python Tutorial: “for” Loop Example

2005-01-15

Python

This is a example of “for” statement. The percent % symbol calculates the remainder of division. The “range(m,n)” function gives a list from m to n-1.

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

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

Python Doc

Python Doc


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. .

perldoc perlsyn

perldoc -f next

perldoc -f last

perldoc -f goto


Related essays:

2005-01
© 2005 by Xah Lee.