Download presentation
Presentation is loading. Please wait.
Published byJulian Beasley Modified over 8 years ago
1
More about Iteration Victor Norman CS104
2
Reading Quiz
3
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.
4
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)
5
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.
6
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?
7
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
8
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
9
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.
10
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.”)
11
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.
12
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.
13
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
14
CQ: What for loop is equivalent to this while loop?: x = 3 while x < 7: print(x) x = x + 2
15
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)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.