Loops in Python

‘While loop’ is the simplest form of loop in Python. But you need to understand it properly. Otherwise it can end up in eating up your memory running the infinity loop. Usually most of the jobs are done by ‘for loop’. But in some special cases, you need to use ‘while loop’. A basic understanding is important.

While Loops

In plain English we often say – ‘While it is true it keeps on running. While it is not true it stops.’ Logically same thing happens here. While a statement is true, the process is going on. You need a mechanism to stop that process. That is important. Otherwise that statement will eat up your memory.
Consider this code:


b = 1
while b < 50:
    print(b)
    b = b + 1
 

What does it mean? It means, the statement ‘b is less than 50’ is true until the suite or block of code is true inside it. Inside the block we wrote ‘b = b + 1’ and before the beginning of the while loop we defined the value of b as 1.
So in each step b progresses by adding 1 in its value and finishes at 49. In the output you will get 1 to 49.

Let us move further. Consider this code:


#!/usr/bin/python3
# simple fibonacci series
# sum of two numbers define the next set
a, b = 0, 1
while b < 50:
    print(b, end=' ')
    a, b = b, a + b
  

The output is quite obvious:

1 1 2 3 5 8 13 21 34

For the beginners, let us write this code in a more human readable way and it will give different output altogether:


#!/usr/bin/python3
a, b = 0, 1
while b < 30:
    print(b, end=' ')
    a = b
    b = a + b
 

Let us explain the steps one by one to understand it properly.
The loop starts with 1. In the first step the value of ‘a’ is 1. In the next step value of ‘b’ is 2. Now the value of ‘a’ is 2 so the value of ‘b’ is 4. Now the value of ‘a’ is 4 so the value of ‘b’ is 8(4+4). Now the value of ‘a’ is 8 so the value of ‘b’ is (8 + 8) = 16. Now the value of ‘a’ is 16. What will be the value of b? It will be 16 + 16 = 32. But 32 are greater than 30. So it will come out from the code suite of while loop.
The output of the above code will be:

1 2 4 8 16

Let us write the whole bunch of code in a new format:


#!/usr/bin/python3
# simple fibonacci series
# sum of two numbers define the next set
a, b = 0, 1
while b < 30:
    print("a = ", a, "=" , "b = ", b, "," , end=' ')
    a, b = b, a + b
print("***********")
a, b = 0, 1
while b < 30:
    print("a = ", a, "=" , "b = ", b, "," , end=' ')
    a = b
    b = a + b

And the output will be:

a = 0 and b = 1 , a = 1 and b = 1 , a = 1 and b = 2 , a = 2 and b = 3 , a = 3 and b = 5 , a = 5 and b = 8 , a = 8 and b = 13 , a = 13 and b = 21 ,
*********** Lines of separation ***********
a = 0 and b = 1 , a = 1 and b = 2 , a = 2 and b = 4 , a = 4 and b = 8 , a = 8 and b = 16 ,

Now hopefully, this explains how the while loops work.

For Loops

The most common loop used in Python is for loop. In fact, essentially almost all kind of looping job can be done through the ‘for’ loop.
There is a reason of course. With the help of for loop we can iterate through python objects and we can iterate through most of the python objects. Let us see one example:


#!/usr/bin/python3
songs = open('file.txt')
for lines in songs.read():
    print(lines, end='')
 

And the output of the song goes like this:

Yo, girl you touched me hard
your loneliness has made me weep
I am a sooo stupid nerd
I thought about the words, I could not keep
So I weep
A stupid nerd

We have a song written over in a file called ‘file.txt’ and we just iterate through this file. We could have iterated through line by line as they are indexed. Consider this code where we just used ‘enumerate()’ function and index value :


# enumerate
songs = open('file.txt')
for index, lines in enumerate(songs.readlines()):
    print(index, lines, end='')

And the output is like this:

0 Yo, girl you touched me hard
1 your loneliness has made me weep
2 I am a sooo stupid nerd
3 I thought about the words, I could not keep
4 So I weep
5 A stupid nerd

Now what does this function ‘enumerate()’ mean? Dictionary says: enumeration is a kind of numbering which is a numbered list. Let us consider this line of code:


strings = "This is a string."
# now we are going to find how many 's' is inside this string
for index, s in enumerate(strings):
    if s == 's':
        print("Hi I am 's' and I am located at position {}".format(index))

And we have an output:

Hi I am ‘s’ and I am located at position 3
Hi I am ‘s’ and I am located at position 6
Hi I am ‘s’ and I am located at position 10

This is extremely useful. You can search any character inside any string. In Python, functions or subroutines are extremely important for reusability of codes. We can call a function for several times and pass many arguments or parameters to get different effects. Now we are going to pass one parameter inside the loops() function. Consider this code below:


#!/usr/bin/python3
def main():
    loops(0)
    loops()
    loops(3)
    
def loops(a = 4):
    for i in range(a, 6):
        print(i, " ")
    print("*************")
if __name__ == "__main__":
    main()

What does this code mean? In loops() function we have passed one parameter a and assigned a value 4. It is the default value. So that in future if we forget to pass any argument the code will not break.
We have called that function three times inside main() function. But with three different values and one of them is NULL that is we have not passed any argument.
The output changes with the new code:

0
1
2
3
4
5
*************
4
5
*************
3
4
5
*************

Now it is obvious that you can play around with this code. You can pass two arguments inside loops() function and control the range() function to get different values.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s