2005-01-15
This is an 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
Reference: Python Doc↗.
Reference: Python Doc↗.
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. .
Reference: perldoc perlsyn↗.
Reference: perldoc -f next↗.
Reference: perldoc -f last↗.
Reference: perldoc -f goto↗.
See also:
Page created: 2005-01. © 2005 by Xah Lee.