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 :
statement1


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.

for price in stock_prices :
value = price * 5
print("Value is " + str(value))


We used the str() funtion to convert the numeric value to string to print it nicely. This will produce the following results:

Value is 50
Value is 40
Value is 45
Value is 55
Value is 60


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.

for index, price in enumerate(stock_prices) :
value = price * 5
print("Value on day " + str(index+1) + " is " + str(value))


The counter starts from ), so we added '1' to each value to start it from day 1. The results are shown below:

Value on day 1 is 50
Value on day 2 is 40
Value on day 3 is 45
Value on day 4 is 55
Value on day 5 is 60


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.

stock_A = [10, 8, 9, 11, 12]
for i in stock_A :
if(i == 11) :
break
print(i)


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.

10
8
9


You may find these interesting

Related Quizzes

Python LoopsPython NumPy