Python Loops

Basic For loop

for x in range(10): print(x)
  • This will repeat the code below it 10 times, and the count will be stored in the variable x (0 through 9).

For loop in a range

for x in range(10,20): print(x)
  • This will loop from 10 up to (but not including) 20.

For loop through array values

myArray = [2,5,2,4,7,3,2,9,1] for x in myArray: print(x)
  • This will loop through each of the values in the list provided, x takes on that value in each repetition.

While loop

x = 0 while x < 5: print(x) x = x+1
  • This will continue repeating while a condition is met.
  • The while loop is useful when you are checking a condition rather than a count.
  • Be careful not to set a condition that cannot be met, otherwise it will keep repeating until it runs out of memory.

Challenge

Create a loop that displays every multiple of 12 up to the 50th.

Completed