In this lesson, we will discuss the for
loop. The syntax of the for loop is
1for name in object :
2 statement1
3
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.
1for price in stock_prices :
2 value = price * 5
3 print("Value is " + str(value))
4
We used the str()
funtion to convert the numeric value to string to print it nicely. This will produce the following results:
1Value is 50
2Value is 40
3Value is 45
4Value is 55
5Value is 60
6
Suppose you also wanted to produce the day number for each of the days. To do so, we can use the enumerate()
function which adds a counter to an iterable value. So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively. The following code shows the usage of the same.
1for index, price in enumerate(stock_prices) :
2 value = price * 5
3 print("Value on day " + str(index+1) + " is " + str(value))
4
The counter starts from ), so we added '1' to each value to start it from day 1. The results are shown below:
1Value on day 1 is 50
2Value on day 2 is 40
3Value on day 3 is 45
4Value on day 4 is 55
5Value on day 5 is 60
6
Example: Break
The below example demonstrates the use of break
statement. For this example, we would like to break and end the loop if the stock price is equal to 11.
1stock_A = [10, 8, 9, 11, 12]
2for i in stock_A :
3 if(i == 11) :
4 break
5 print(i)
6
The loop will execute normally. Each time, it will check if i
is equal to 11, if not, it will proceed to print the value of i
. If i
becomes equal to 11, then the break
statement will be executed and the loop will be exited.