Loops Flashcards
What is a loop?
a loop is a control structure that is used to perform a set of instructions for a specific number of times
What are loops mainly used for?
for traversing over data structures (i.e. lists, tuples, sets, etc), performing a set of operations on each element in the data structure
What is a while loop?
A while loop keeps iterating over a set of operations as long as a certain condition hold true
the logic of a while loop is: while this condition is true, continue looping thru the set of instructions
therefore, and unlike a for loop, we don’t always begin the loop knowing the number of iterations
What is a for loop?
a for loop uses an iterator to traverse a list,
The iterator begins as the first element of the sequence and continues looping thru the set of instructions, updating the iterator to be the next element in the sequence with every loop
How do you decide to use recursion vs iteration?
use Recursion when: we need to divide data into different chunks
use Iteration when: traversing data and also when we don’t want the program’s scope to change