Python (Chapter 3.1) : FOR loop (Series)


For any type of consultation, query or doubt. You may contact to the following: (+91) 9804 436 193 or, debabrataguha20@gmail.com 
and join the group  https://www.facebook.com/groups/331231161093613/


Hope you have already practised a good amount of programs with nested if-else statements. So now we will learn how to do repetitive work in Python. In the world of logic and algorithm and brain storming , the most important thing is to handle loops. Here in this chapter we will learn to form loops with the help of “for in range” keyword. Most of us think, there is not much to learn on the basic structure of FOR loop. But still I will request you to go through the basic structure of FOR loop once again. For the newcomers, it is must to focus more on this chapter, as this is the most important chapter of your programming journey. If you are good at FOR loops, then you are good at programming logics as well. Your grading as a future programmer will be decided during these for loop chapters.

We will learn total 5 things in this chapter.



First thing to learn :

First we will try to learn the structure of FOR loop. So starting with a simple program to print all the numbers from 1 to 10.. Obviously Solution should not be like writing PRINT() 10 times. Or to write all the numbers inside print (‘1,2,3,4,5,6,7,8,9,10’)

So to solve this, we will introduce a FOR loop. The basic structure of FOR loop is as follows.

for variable in range ( Start Value> , <Last Value> +1 , <Steps> ) :
               Loop body ..
               It may consist multiple lines.



1st part is <Start Value> à means the starting value of the variable ( Initial values before we start the FOR loop)

2nd part is <Last Value> à Last value of the variable till when the loop will repeat itself. If it crosses the last value of the variable, then the loop will be stopped.

3rd part is <step> à this part, we can set values for the next iteration. Means the next value of the variable. This part is optional. If you do not mention anything, the value of the variable will be incremented by 1. Keep it in mind.

4th part is Loop body à it contains few lines that would run again and again. You may write PRINT “HI” in FOR loop body. That means Multiple “HI” will be printed in the output window.





I know, this is confusing for new comers. But believe me when you will see the examples, it will be the easiest thing in the world. So directly going to the examples, then we will repeat the above 4 parts again with a reference to the example.

So now, to print 1-10 in the output window, we can write the following FOR statement.

for i in range ( 1   ,   10+1 ) :
print (i)
So let us revisit to our statements once again with a reference to the lines of above program.






As I said,

1st part is <Start Value> à means the starting values of the variables ( Initial values before we start the FOR loop). Here we are setting 1 to the variable “i” before we enter into FOR loop.

2nd part is <Last Value> à Loop will iterate till the last value of “i” . Here the <Last Value> is 10. 

for variable in range(Start Value> ,<Last Value> +1,<Steps>):

As per the above style 10 +1 means <Last Value> is 10. Keep in mind, we need to write “1 extra value in the sequence”, that’s why <Last Value> +1 will be written always. So the loop will iterate till 10, whereas we need to write “10+1” in the program.

Instead of for i in range ( 1 , 10+1 ) : , we can also write for i in range ( 1 , 11 ) :


3rd part is <Step> à By this part we can set values for the next iteration. As nothing is written after “10” in this program, means by default it will be 1 as said above. In 1st run the value of i is 1, then into the next run , the value of i will be 2 and checking if it lesser than 10 or not, if TRUE, then it will print 2 and it will be incremented to 3 and so on..


4th part is Loop body à it contains few lines that would run again and again. In the above program, it will print the value of i by the line “print (i) “. So in output window, we will be able to see 1,2,3,…10.






**Common Error**:

for i in range ( 1 , 11 ) :

Keep in mind that the last value of the variable will be 10 here. The <Last Value> will be 1 less than the value mentioned in the range function. We need to write “1 extra value in the sequence” in the program.

Though it is written like range (1,11) , but in output screen we can see 1,2,3, ..,9, 10.

You have to keep this in mind throughout your python programming journey. I can challenge you somewhere in your programming life you will surely do this mistake. So keep this concept always in mind. 11 means it will run till 10.

Always try to avoid this common error. **







Using this concept, now let us calculate the output for the following code snippets:

Code 1:
for i in range ( 5 , 9 ): 
print ( i )
Output:
                        5
6
7
8
Explanation:
i is starting from 5 and running till 8 ( means 1 less than 9), each time incrementing by 1. Similar to for i in range ( 5 , 8+1 ):





Code 2:
for i in range ( 3 , 16 , 4): 
print ( i )
Output:
                        3
7
11
15
Explanation:
                      i is starting from 3 and running till 15 ( 1 less than 16), each time incrementing by 4. Third number indicates the step. In  3rd place “4” means i will be incremented by 4 every time.






Code 3:
for i in range ( 4 , 9 , 2): 
print ( i )
Output:
                        4
6
8
Explanation:
                      i is starting from 4 and running till 8 ( 1 less than 9), each time incrementing by 2. Third number indicates the step. In  3rd place “2” means i will be incremented by 2 every time.







Code 4:
for i in range ( 4 , 10, 2 ): 
print ( i )
Output:
                        4
6
8
Explanation:
i is starting from 4 and the last value is 9 ( 1 less than 10 ), each time incrementing by 2. The output will be same as code snippet 3.






Code 5:
for i in range ( 10 , 5, -2 ): 
print ( i )
Output:
                        10
6
Explanation:
i is starting from 10 and the last value is 6 (as it is decreasing , the last value will be 6). But in Range function, we need to mention “1 extra value in the sequence”. So in range function “5” means series will be till 6.

In third place, “-2” means, each time decrementing by 2. We will check the next code snippet to find what will happen in case of wrong step values.





Code 6:
for i in range ( 20 ,10 , -1 ): 
print ( i )
Output:
                        20
19
18
17
16
15
14
13
12
11 
Explanation:
                              <Start Value> is 20 and <Last Value> is 11.







Code 7:
for i in range ( 10 , 4 , -2 ): 
print ( i )
Output:
                              10
                              8
                              6
Explanation:
<Start Value> is 10 and <Last Value> is 5. But as decreasing by 2. Till 5 all the even numbers will be printed.






Code 8:
for i in range ( 10 , 4 , 2 ): 
print ( i )
Output:

Explanation:
Nothing will be printed as i is starting from 10 and the last value will be 5 , and we are telling i to be incremented by 2 each time. Computer will be confused and will not print anything.







Code 9:
for i in range ( 1 , 10, 0 ): 
print ( i )
Output:
                              error
Explanation:
Here the value of i will be starting from 1. As the value of i is not increasing, it can not reach to 9. So this loop will be an infinite loop again. So python has restricted the permission. It will show an error if you put zero in the third place.







Code 10:
for i in range ( 1 , 11 ): 
print ( i )
print ( ‘ atlast the value is ‘ , i )
Output:

                        1
4
5
6
7
8
9
10
atlast the value is 11

Explanation:

It is now obvious that <First Value> is 1 and <Last Value> is 10.

Concentrate on the last line. After the loop the value of i is 11.. It has to be.. Because to put an end of the loop, the value of i should reach to 11. So that it will cross 10 and the loop will end. So if we try to print the value of i outside of the loop, it will show 11. 

                        one important thing , proper indentation defines the definition of for loop body.





Second thing to learn :
In all above programs , numbers are getting printed in different line. What if I want to print them in the same line. use following code:

Code 11:
for i in range ( 1 , 11  ): 
print ( i , end = ‘ ‘)
Output:
1 2 3 4 5 6 7 8 9 10

Values will be printed in different line normally.  print statement always print something and then change the line. But if you put a phrase like  , end = ‘ ‘ after the PRINT statement, Line would not be changed.





Third thing to learn :
Now if anyone asks to print 10 stars (*), what would you write? It would be the same code, but printing * instead of i ..

Code 12:
for i in range ( 1 , 11  ): 
print ( ‘ * ‘ , end = ‘ ‘);
Output:
* * * * * * * * * *
Explanation:
Simply, loop is iterating 10 times and is printing 10 stars.




Code 13:
for i in range ( 1 , 11  ): 
print ( ‘ # ‘ , end = ‘ ‘)
Output:
# # # # # # # # # #
Explanation:
Simply the loop is iterating 10 times and printing 10 hashes (#).





Code 14:
k = 100
for i in range ( 1 , 11  ): 
print ( k , end = ‘ ‘)
Output:
100 100 100 100 100 100 100 100 100 100
Explanation:
Simply the loop is iterating 10 times (11 – 1 times ) and printing the value of K 10 times. Means the loop will print the value 100 ten times.





Code 15:
k = 100
for i in range ( 1 , 11  ): 
print ( k , end = ‘ ‘)
k=k+5
Output:
100 105 110 115 120 125 130 135 140 145
Explanation:
Simply the loop is iterating 10 times and printing the value of K 10 times. At first, the loop will print the value 100 and the value of K will be incremented to 105. Then it will print 105 and the value will be incremented to 110 and so on.


So we have learnt 2 things from code snippet 15:


 a. We can use one variable to control the loop and another value to print the elements in output window.

b. We can print 10 terms or n terms of a series. Means we can print a series without giving the limit.

If you look closely, we have not put any limit like for k in range  (100 ,145+1) in the last program. Even we did not know that the 10th term of the series will be 145. We are printing 10 terms only by the following FOR loop.

k = 100
for i in range ( 1 , 11  ): 
print ( k , end = ‘ ‘);
k=k+5

Number of terms are being controlled by the variable i whereas the values are being hold by the variable k.





So please follow following 2 code snippets. It will clarify what I want to mean.

Code 16:
# printing the series 7  11  15  19  23  …..  <=50
for i in range ( 7 , 51, 4  ): 
print ( i , end = ‘ ‘)
Explanation:
The above series will surely be terminated by 50. It may end at 47 or 48 or 49 , I have not calculated the exact value.. But it will be surely on or before 50.





Code 17:
# prointing the series 7  11  15  19  23  …..  10 TERMS
                        k = 7
for i in range ( 1 , 11) :
print ( k , end = ‘ ‘)
            k=k+4
Explanation:
If we try to print only 10 terms of this series, then we can calculate the 10th term on paper and then put the limit at FOR loop condition. But it will be wiser to use the logic of variable K that we have used above. Here the FOR loop will be iterating 10 times with the help of variable i . But in output window, the value of k will be printed and k will be updated accordingly to print the desired series.





Again we are taking 1 more program examples as below:

Code 18:
#printing the series 5  15  45  … 6 terms 
                        k = 5
for i in range ( 1, 6+1 ): 
                                    print ( k , end=’ ‘)
k = k * 3






Fourth thing to learn :
Sometimes we are confused with the following types of program where some numbers are with positive sign and some are with negative sign.

printing the series 7  -11  15  -19    upto 10 terms
printing the series 7  -11  15  -19    <=50

I will always suggest to write the code for the series first by omitting the positive and negative signs. After completing the series without any sign, then only think how can we bring that signs alternatively.


Code 19:
#printing the series 7 -11 15 -19    upto 10 terms
k = 7
for i in range ( 1 , 11 ):
            if ( i % 2 == 0 ):
                        print ( -k , end = ‘ ‘ )
            else:
                        print ( k , end = ‘ ‘ )
            k = k + 4
Explanation:
If you look closely, if we omit positive and negative signs, it is similar with the code snippet number 17. So for that reason FOR loop statements are same for both code 17 and 19. Extra thing is the IF-ELSE part inside the FOR loop body. On the basis of some condition, sometimes it is positive, sometimes it is negative. Here the condition is , number is negative in each 2nd , 4th, 6th term. Means k will be negative when i is an even number.



Code 20:
# printing the series 7 -11 15 -19 … < =50 
a = 1
for i in range ( 7 , 51, 4):
            if ( a % 2 == 0 ):
                        print ( -i , end = ‘ ‘)
            else:
                        print ( i , end = ‘ ‘)
            a = a + 1
Explanation:
If you look closely, if we omit positive and negative signs, the series is similar with the code snippet number 16. So for that reason, FOR loop line is almost same for both code 16 and 20. Extra thing is the IF-ELSE part inside the FOR loop body. On the basis of some condition, sometimes it is positive, sometimes it is negative. Here the condition is , number is positive in each 2nd , 4th, 6th term. So to count the terms, we have introduced an extra variable named “a” which is just counting the number of terms. Means “i” will be positive when “a” is an even number.





Fifth thing to learn :
The last part of this chapter is to print the sum of the series. It is really easy to calculate the sum of any series. I am saying if we can print the series , then we can surely calculate the sum by 3 simple statements.

Statement 1: introduce a variable named “sum” with value zero before we start the FOR loop. Inside this new variable “sum” , we are going to collect the sum.

Statement 2: Inside the FOR loop body we will not print the variable , rather we will put the printable value into “sum”.

Statement 3: After the loop , print the variable “sum”


Let us take code snippet number 13 and 16..

Code 16 :: calculating SUM:

#printing the SUM of the series 7  11  15  19  23  …..  <=50
sum = 0
for i in range ( 7 , 51 , 4 ):
sum = sum + i
print ( ‘ the sum is ‘ , sum)



Code 19 :: calculating SUM :

#printing the sum of the series 7 -11 15 -19    upto 10 terms
sum = 0
k = 7
for i in range ( 1 , 11 ):
            if ( i % 2 == 0 ):
                        sum = sum + ( -k )
            else:
                        sum = sum + k
            k = k + 4
print ( ‘ the sum is ‘ , sum )


I can guarantee , if you can print the series anyhow, then by applying these simple 3 statements you can find the sum of that series. These 3 steps will be applicable to all the series programs. If not, you can mail me one example. So to print the sum of any series, first focus on printing the same series.






Now you have to do some hands-on before moving to the next chapter. As I previously said, these FOR loop chapters will decide your strength in this programming language. You can start solving the exercise “For Series” from the above said Facebook group. In case of any confusion, you may contact me on the abovesaid mail or whatsapp number.  Best of luck..




Comments

Popular posts from this blog

Java concepts Theory

About Myself ..