Module 7 - For Loop Flashcards
What’s a For Loop?
Runs for a specified number of times, designed to work with a sequence of data items (iterates once per item)
What is the syntax for a For Loop?
for variable in [val1, val2, val3,…}:
____statements
What is a target variable?
The variable which is the target of the assignment at the beginning of each iteration
Its purpose is to reference each item in a sequence as a loop iterates
What is the “in” operator in a for loop?
It allows the for loop variable to take on one value at a time during each iteration automatically so you won’t need to count or advance the loop variable
T or F: The control variables can only iterate on numerical lists.
False. It can iterate on any list - integer, float, string
What does the range function do?
Returns sequence values
How many arguments can a range function have?
1, 2, or 3: end; start and end; start, end, and step
What does range(5) return?
[0,1,2,3,4]
Default start value is 0, default increment is 1
NEVER include the end value (5) in the sequence!! Stop at the value before it
What does range(1,5) return?
[1,2,3,4]
The start value (1) is now specified
What does range(1,9,2) return?
[1,3,5,7]
The start value (1) and increment (2) are specified
How do you generate a sequence of numbers in descending order? e.g., 10 to 1?
you can use range function and make step negative:
range (10, 0, -1)
What’s a nested loop? What’s an real-world example of a nested loop?
Loop contained in another loop
Ex: Analog clock- hours and minutes hands
T or F: Outer loop goes through all of its iterations for each iteration of inner loop
False: Inner loop goes through all of its iterations for each iteration of outer loop
Inner loops complete their iterations faster than outer loops
How to calculate total iterations in a nested loop?
Total number of iterations in nested loop: number_iterations_inner x number_iterations_outer
When should you use a for loop? When should you use a while loop?
For Loop- when you need to perform the same action on every item in a list or character in a string
While Loop- when you need to perform a repeated operation but you don’t know ahead of time how many iterations will be needed