MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1＆1

# Python, Ruby, Perl: Loop Examples

Xah Lee, , …,

## Python

This is a example of “for” loop.

```# -*- coding: utf-8 -*-
# python

aa = range(1, 10) # creates a list, 1 to 9
for xx in aa:
print xx                    # prints 1 to 9
```

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

```#-*- coding: utf-8 -*-
# python

for x in range(1, 10):          # 1 to 9
print x
if x == 4:
break                   # prints 1 to 4
```

http://docs.python.org/reference/compound_stmts.html#for

```#-*- coding: utf-8 -*-
# python

x = 1
while x <= 9:
print x
x += 1
```

http://docs.python.org/reference/compound_stmts.html#while

## Ruby

```#-*- coding: utf-8 -*-
# ruby

aa = 1..9                     # creates a array 1 to 9
for xx in aa do
p xx
end                               # prints 1 to 9
```

Note: Ruby also supports loop controls {break, next}.

```#-*- coding: utf-8 -*-
# ruby

for xx in 1..9 do
p xx
if xx == 4 then break end
end                             # prints 1 to 4
```
```#-*- coding: utf-8 -*-
# ruby

x = 1;
while x <= 9 do
p x
x += 1
end
```

## Perl

This is similar code in Perl.

```#-*- coding: utf-8 -*-
# perl

@aa = (1..9); # creates a array 1 to 9
for \$xx (@aa) {
print \$xx
}                               # ⇒ 123456789
```

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

```#-*- coding: utf-8 -*-
# perl

for \$xx (1..9) {
print \$xx;
if (\$xx == 4) {
last;                       # break
}
}                               # ⇒ 1234
```
```#-*- coding: utf-8 -*-
# perl

\$x = 1;
while (\$x <= 9) {
print \$x, "\n";
\$x++;
}
```