Loops with for and while

From Training Material
Jump to navigation Jump to search


Unconditional loops with for

For loops require a sequence of items that is iterated over. This can be a list, a tuple, a string, a dictionary or any Python object that behaves like one of them (e.g. a file). Examples:

for i in range(3):
print i

for char in 'ABCD':
print char

for elem in [1,2,3,4]:
print elem

Conditional loops with while

While loops require a conditional expression at the beginning. These work in exactly the same way as in if.. elif statements.

i = 0
while i < 5:
print i
i = i + 1

When to use for

  • When the number of iterations is known at the beginning.
  • Printing numbers, concatenating a list of strings.
  • Modify all elements of a list.

When to use while

  • When there is a exit condition.
  • When it may happen that nothing is done at all.
  • When the number of repeats depends on user input.
  • Searching for a particular element in a list.