Chapter 5 Loops
Keyword | Action |
---|---|
for | loop |
continue | skips over the remaining lines and repeats |
break | quits the loop |
There are situations, where similar code-block needs to be written many times. An example is shown below.
Try -
print( "5 times 1 is", 5*1 )
print( "5 times 2 is", 5*2 )
print( "5 times 3 is", 5*3 )
print( "5 times 4 is", 5*4 )
print( "5 times 5 is", 5*5 )
print( "5 times 6 is", 5*6 )
print( "5 times 7 is", 5*7 )
print( "5 times 8 is", 5*8 )
print( "5 times 9 is", 5*9 )
print( "5 times 10 is", 5*10 )
The above code prints the multiplication table for 5, but it is too tiring to type. Imagine if you have to type the same multiplication table to 5 times 100.
Python provides a shortcut for such situations using the keyword ‘for.’ The following code produces the same output as the long code shown above.
for i in [1,2,3,4,5,6,7,8,9,10]:
print( "5 times", i, "is", 5*i )
print( "completed for loop" )
The keyword ‘for’ is used to repeat a block of code many times. That block of code needs to follow the line with ‘for’ statement with an indentation.
Here is how the above code works. On the ‘for’ statement, Python creates a variable i with value = 1 and runs the code in the indented block. After completion, i becomes 2, 3, etc. up to 10 based on the list, and each time the indented block is executed with the new value of i. Once the final value of the list is reached, Python continues with the following unidented statement and print(s “completed for loop.”
It is possible to condense the code further. Instead of writing the entire list, you can use the range() function to auto-generate the list, as shown below.
for i in range(1,11):
print( "5 times", i, "is", 5*i )
print( "completed for loop" )
Converting the above code to type the multiplication table up to 5 time 100 is rather easy. Just replace 11 in the range function to 101.
5.1 Expansion of ‘for’ Loops
Here are some examples to help you better understand ‘for’ loops. With these examples, we are giving you the code using ‘for.’ You need to write the expanded code, where you do not use ‘for.’
5.1.1 Expand -
for i in [1,3,5,7,9,11,13,15,17,19]:
print( "5 times", i, "is", 5*i )
Answer -
print( "5 times 1 is", 5*1 )
print( "5 times 3 is", 5*3 )
print( "5 times 5 is", 5*5 )
print( "5 times 7 is", 5*7 )
print( "5 times 9 is", 5*9 )
print( "5 times 11 is", 5*11 )
print( "5 times 13 is", 5*13 )
print( "5 times 15 is", 5*15 )
print( "5 times 17 is", 5*17 )
print( "5 times 19 is", 5*19 )
5.2 What will this code do?
Sometimes, we are given a code with “for” and need to work out its details. Here is an example that I am giving you as an exercise. Tell me what it will print and why.
x=7
for i in [1,2,7,9]:
x=x+7*i*(i-1)
print(x)
5.2.1 Hint
Check how we went from writing the multiplication table in detail to for loop. This time, you need to reverse the process.
5.2.2 Solution
These kinds of problems are important for understanding for
loops. When you develop your own code, you will often come across situations like this. You have a for
loop and the result is not the same as what you expected. So, you have to figure out what your loop is doing, and here is how it is done.
If you remember, we had the multiplication table for 5 written explicitly (i.e. without for
loop) and we condensed into for
loop. This time, we have code with for
and we will write it without for
.
x = 7
i = 1
x = x+7*i*(i-1)
i = 2
x = x+7*i*(i-1)
i = 7
x = x+7*i*(i-1)
i = 9
x = x+7*i*(i-1)
print(x)
So, essentially you copy and paste the same code four times, and put different values of i in front. Now the code is easier to understand.
In third code line, x = x + 7 * 1 * 0
In fifth code line, x = x + 7 * 2 * 1
In seventh code line, x = x + 7* 7 *6
In ninth code line, x = x + 7*9*8
So, the final answer is 7 + 7*1*0 + 7*2*1 + 7*7*6 + 7*9*8 = 819
5.3 What will this code do?
x=7
for i in [2,1,0]:
x=i-2
print(x)
5.3.1 Answer -
x = 7
x = 2-2
x = 1-2
x = 0-2
print( x )
5.4 Explain the outputs of the following two codes.
a=[1,3,2,0]
for i in a:
print( i,"a[i]+8=",a[i]+8 )
a=[1,3,2,0]
for i in range(len(a)):
print( i,"a[i]+8=",a[i]+8 )
5.4.1 Solution
The first code can be rewritten as -
a=[1,3,2,0]
for i in [1,3,2,0]:
print(i, "a[i]+8", a[i]+8)
We can now expand the loop as -
a=[1,3,2,0]
i=1
print(i, "a[i]+8", a[i]+8)
i=3
print(i, "a[i]+8", a[i]+8)
i=2
print(i, "a[i]+8", a[i]+8)
i=0
print(i, "a[i]+8", a[i]+8)
You can confirm on your sandbox that the output of this long code is the same as the original code. Then you can work out the long code by using different values of i in the print statement.
5.5 Using ‘for’ over String
Try -
S = "alabama"
for c in S:
print( c )
print( c.upper() )
When ‘for’ is written on a string, the loop variable takes the values of each character of the string. Therefore, the above code print(s both lowercase and uppercase versions of the characters of “alabama” in separate lines. If you add a comma after the print( statements, the characters will all be printed in the same line separated by spaces.
5.6 Keywords ‘break’ and ‘continue’
Sometimes it is necessary to break out of ‘for’ loop, if certain conditions are satisfied. The keywords ‘break’ and ‘continue’ help in interrupting the standard flow. They are explained in the following section with respect to ‘while’ loops, but work for ‘for’ in a similar manner.
5.7 Summary
Python keyword ‘for’ executes the same block of code many times. The block of code needs to be written immediately after the ‘for’ statement with indentation. After completion of the ‘for’ block, Python continues with subsequent non-indented code.
The ‘for’ statement can state a changing variable given based on a list, dictionary or string. The block of code executing in each ‘for’ run uses the new value of the variable. Later we will learn that the ‘for’ statement can be extended for other kinds of custom variables known as ‘iterables.’
One weakness of ‘for’ is that the values of the looping variable need to be know a-priori. There are situations, where the next value of the looping variable is determined based on the execution of the loop. Such codes are written using the Python keyword ‘while,’ as explained in the following section.