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.

Continue reading “Loops in Python”

Function generator in Python

Normally when we use for loop and range() method in Python it stops at just before the range we mentioned.

It looks like :

for i in range(10):
print(i)

And it reads from 0 to 9 and stops.
Basically through the range() method of Python, we pass three variables – start, stop and step. In between these three variables, by default the values of ‘start’ and ‘stop’ are pre-set. ‘start’ is 0 and ‘stop’ is 1. So it starts from 0 and each step it iterates 1 step and stops at 9. In it the ‘stop’ value remains inconclusive.
But we can make the ‘stop’ value conclusive by the following method:
Continue reading “Function generator in Python”