banner

© 2004-19 ict4u.net

Python Iteration

Iteration (looping) means being able to execute a block of code a number of times.
This is useful if you want to run the same code over and over again, each time with a different value. Iteration is really useful when you are working with arrays.
Python has two loop structures:

For Loops
Afor loop is used for iterating over a sequence for example a list, dictionary or string. Before the loop executes the number of times the code will loop is finite.
  • set by a loop counter
  • set by the number of characters in a string
  • set by the number of elements in a list
  • set by the number of items in a data structure such as a dictionary
While Loops
Awhile loop is used to iterate code waiting for a condition to change.
This might for example be waiting for the user to type a certain value at the keyboard.
Before the loop executes the number of times it will loop cannot be determined and could be infinite.
    Method Description
    For Loop simple for loop controlled by a numeric variable
    For loop with 2D List Print a 2D list using a for loop
    While Loop Loop While a condition is true

    Notes: the condition is tested at the beginning of the loop and the code may not get executed

    While Else Loop Loop While a condition is true, with an else clause after the loop has completed