Loop structures: Difference between revisions

Content added Content deleted
(Simple case first, comments)
Line 747: Line 747:
===for===
===for===


Typically for is used to iterate over items in an iteratable:
for i in range(10):
print i
else:
# break was not called
foo()


for x in ["foo", "bar", "baz"]:
for x in ["foo", "bar", "baz"]:
print x
print x


It is also used to create indexes:
''Does range(10) return an array? The above two examples may be redundant.''

for i in xrange(10):
print numbers[i]
Optional else is executed if break was not use to stop the loop:

for i in numbers:
if item < 0:
break
else:
print 'all numbers are positive'


==[[Ruby]]==
==[[Ruby]]==