Week 7: More Loops Flashcards
What will come out of this:
for counter in range(5, 0, -1):
print(counter)
print(“Blast off”)
5
4
3
2
!
Blast off!
What will come out of this:
total = 0
for i in 5, 7, 11, 13:
print(i)
total = total + i
print(total)
5
7
11
13
36
How can we establish the counter to step according to other increments?
Example:
for counter = 5 to 20, step 5
output:
5
10
15
20
Complete the 2 missing questions for Loop design questions:
1. What steps in your code need to repeat?
2. How many times do these steps need to repeat?
- Does the user determine when the loop ends?
- What variable or condition needs to exist for the loop to end?
What are Nested Loops?
Loop within a loop, outer loop with at least 1 inner loop, each loop executes based on different conditions, the inner loop is dependent on the outer loop condition.
In an example of a clock, name 1 iteration it goes through.
24 hours = 1 days, 60 minutes = 1 hour, 60 seconds (inner inner)= 1 minute.
60 iterations to be 1 minute(inner), causing minute hand to move.
Then the minute hand moves 60 iterations, for 1 hour(outer). Etc.
How to know what goes in outer and inner loops?
outer loop controls the broader context or the larger set of iterations.
inner loop handles the more detailed or nested iterations within each iteration of the outer loop.
Example, seeing the possibilities of pairs from 2 lists. The outer loop can iterate over the first list, and the inner loop can iterate over the second loop.
In the Python shell, what can you type to get help with the range(n) function?
help(range)