For Loop in Python

In Python, we will learn about the two statements that provide explicit looping. They are for and while loops.

There are two statements that can be used to explicitly control looping. They are break and continue. The break statement causes an exit from the innermost loop that is currently being executed. The continue statement immediately causes control to return to the start of the loop. The next iteration of the loop (if there is one) is then executed. No statement below continue in the current loop is evaluated.

In this lesson, we will discuss the for loop. The syntax of the for loop is

for name in object :

Here object can be a list, a Numpy array, or any other data structure such as a Pandas data frame. For each element in object the variable name is set to the value of that element and statement1 is evaluated. Basically, the loop iterates over the object.

Example: Stock Prices

Let's say we have a list of the prices of a stock over the past 5 days. Also assume that we are holding 5 units of this stock.

stock_prices = [10, 8, 9, 11, 12]

If you want to calculate the value of your holding in this stock for each of the days, you can use the for loop to do so.

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.

Related Downloads