Core Python / Iteration#
What is iteration, and why is it important in programming?
With iteration, we repeatedly execute parts of a program. Many tasks require this repetition. For example, if need to calculate the returns for a stock portfolio, we need to iterate over each entry in the portfolio, comparing the current stock price to the purchase price.
Explain the differences between while and for loops. Which typically executes for an indeterminate number of times?
The
while
allows us to execute(repeat) a code block an indeterminate number of times as long as a given condition is met.The
for
loop is used to iterate a fixed number of times (e.g., over the entries in a list, over a sequence of numbers, etc.)How do you iterate over a list in Python using a for loop?
tickers = ['TLSA','APPL','T','F','IBM','WFC'] for symbol in tickers: print(symbol)
What is the purpose of a
break
statement?The
break
statements move processing to immediately after the loop once a condition is found that no longer requires any further processing in the code block or no longer needs to evaluate any further loop iterations.How do you create an infinite loop in Python using a while loop? Provide an example of when such a construct is used.
Use a
while
loop with a condition that allows evaluates toTrue
.while(True): # perform some evalation
Web servers continually process requests. The server waits for a request to come, processes that request, and generates the response to send back to the client. This loop repeats until the server shuts down.
What is the significance of a sentinel value? How would such a value be used in a loop?
A sentinel value is a special value, typical of the same type of the current item, that is used to signify a specific event, such as the end of input. When this value is reached, a
break
statement may be used to exit the loop.