More about Iteration Victor Norman CS104
Reading Quiz
For Loop Review Syntax: for in : (i.e., the body) are executed a fixed number of times – the number of items in. “iterates” through -- takes the next value on each time through the loop.
For loop Review continued range() is very useful to create a. range(start, stop, step) When used in place of, let’s you iterate through loop multiple times. E.g., for i in range(20, 31): print(i)
While loop syntax while : “As long as the Boolean expression is True”, do the statements. Why have both for-loop and while-loop in Python? While loop is Indefinite iteration For loop is definite iteration: loop is done a prescribed # of times. No Boolean test is done.
CQ: In a while loop like this: while : Is it a good idea for the statements in the body to change any variables’ values that are used in the Boolean expression?
CQ: What is printed by the following code? (Output is on one line to save space.) x = 6 while x > 4: print(x) x = x - 1
CQ: What is printed by the following code? (Output is on one line to save space.) x = 0 while x < 2: y = 1 while y < 4: print(x + y) y = y + 2 x = x + 1
Exercise: Write code to do this (where user enters any name or q): Enter your name (q to quit): Arthur Hello, Arthur Enter your name (q to quit): Merlin Hello, Merlin Enter your name (q to quit): q Goodbye.
Answer name = input(“Enter your name (q to quit):”) while name != “q”: print(“Hello,” + name) name = input(“Enter your name (q to quit):”) print(“Goodbye.”)
break Statement (not in the book) only can be used inside a loop body instantly stops the loop and jumps to the next statement after the end of the loop. useful for when you have an if in a loop and want to stop e.g., when you are searching and find the item.
continue Statement (not in book) only can be used in body of a loop. instantly jumps back up to the next iteration of the loop. very useful when “filtering” out stuff.
continue Example earthquakes = [ … ] for e in earthquakes: # filter out earthquakes that are too small if magnitude(e) < 5.0: continue # skip this earthquake e # more filters here, perhaps… print(e) # only prints large earthquakes
CQ: What for loop is equivalent to this while loop?: x = 3 while x < 7: print(x) x = x + 2
CQ: What does this code do? inputs = [ … some list of strings … ] for elem in inputs: if elem == ‘q’ or elem == ‘Q’: break if elem[0] == ‘#’: continue doStuffWith(elem)