Python Iteration

iteration - a set of instructions is repeated until a specific condition is met
loop - a block of code the will repeat over and over again

for loop

Uses keywords for and in
Syntax:

for item in containter:
  do_something

Example:

animals = ["Dog", "Cat", "Cow"] #container
for animal in animals: #item is defined in the for loop
  print(f"{animal} was here.") #not sure why the 'f' is necessary?
  
  
## Dog was here.
## Cat was here.
## Cow was here.

while loop

As long as the condition that follows while is TRUE the loop will be continuously executed

while condition:
  do_something

The code below will produce an infinate loop! If you run it ^Ctrl + C to escape (or maybe just don’t run it)

while True:
  print("working...")

break to exit a loop

for item in container:
  if thing_happens:
    break #exit the loop

Example:

str = ["G", "C", "A", "G", "C", "A", "G", "C", "A", "T", "A"]

for letter in str:
  print(letter)
  if letter == "T":
    break


  
## G
## C
## A
## G
## C
## A
## G
## C
## A
## T

The last “A” isn’t printed because the loop stopped after encountering a “T”

continue

if the continue keyword is reached in a loop the current iteration is stopped and the next is started

for item in container:
  if thing_happens:
    continue #go to the next iteration
  do_a_thing

Example:

for l in 'spayed': #using 'l' here for the item instead of 'letter'
  if l == 'y': #if a 'y' is encountered upon iteration
    continue #go do the next thing
  print(l)
  
  
## s
## p
## a
## e
## d

The result is printing ‘spaed’ instead of ‘spayed’

else in loops

else is executed when the loop exhausts the list (for loops) or when a condition is false (while loops) but not when the loop is terminated by break. Syntax

for item in container:
  do_a_thing
else: #belongs to the for loop, there is no if statement
  do_a_different_thing

here
working on this

for n in range(2, 10):
  for x in range(2,n):
    if n % x == 0: #modulo returns the remainder of dividing two numbers
      print(n, 'equals', x, '*', n//x)
      break
  else: 
    print(n, 'is a prime number')
    
## 2 is a prime number
## 3 is a prime number
## 4 equals 2 * 2
## 5 is a prime number
## 6 equals 2 * 3
## 7 is a prime number
## 8 equals 2 * 4
## 9 equals 3 * 3