Python Loops

According to Google – “In computer programming, a loop is a sequence of instructions that is continuously repeated until a certain condition is reached.”

Now try to understand this.

Why Loops are so important?

Consider a situation- What if I ask you to print “Hello World” 4 times in Python. You would probably do something like this.

print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")

But now what if I ask you to print the same message 400 times. What would you do? Would you write the same line of code 400 times?
You can of course do that but that’s not a smart approach. Moreover, it would take a lot of time to do so. This is where a loop comes into picture.

Now watch this-

i = 1
while(i <= 400):
	print("Hello World")
	i+=1

If you execute the above code, it will print the message “Hello World” 400 times! It is only four lines of code but it will generate the same output we need. Instead, we don’t have to write the print(“Hello World”) statement 400 times!

Let us try to understand the code

The first line of code is called the initialization. We have initialized the variable i with a value of 1. Now, the while loop will execute as long as the value of i is less than or equal to 400. So in the first iteration, the value of i is 1, it is less than 400, so the control will enter the loop, execute the print statement, and increment the value of i by 1. The control will again go to the line number 2 and check whether the condition written in while is true or not. Since the value of i is 2 (incremented by one in the previous iteration), it is still less than 400. The control will again go inside the loop, execute the print statement and increment the value of i by 1 again.

This process will be repeated until the value of i is incremented to 401. In the last iteration of the loop(When the value of i is 400), the print statement will be executed for the last time and again the value of i will be incremented by 1(making it 401). Again the control will go to line number 2 and check the condition. Since 401 is not less than or equal to 400, the loop will be terminated at this point.

Types of loops in Python

  • while loop
  • for loop

The while loop: The loop used in the above example is called a while loop. It executes the code written inside it as long as the condition written inside it is true.

Syntax of while loop:

while expression:
    Code

Example:

i = 1
while i<= 4:
        print("Hello")
        i += 1

Output:

Hello
Hello
Hello
Hello

Infinite while loop

An infinite while loop is one in which the condition always remain true

Example:

i = 1
while i <= 2:
        print("Hello")

This loop will run forever until the memory is full.

You can also use boolean value to run a loop

i = True
x = 1
while i == True:
        print("Hello")
        x += 1
        if x > 4:
                i = False

For loop: The for loop executes over a collection. Like a string(Since a string is a collection of characters), a list, a tuple or a dictionary.

Example:

for i in 'hello':
	print(i)

Output:

h
e
l
l
o

The i variable points to a specific character in the string for every iteration of the loop. That is, for the first iteration, the value of i will be ‘h’, for the second iteration it will be ‘e’ and so on.

Counting the characters in a string with a loop

mystring = "Singapore"
counter = 0
for i in mystring:
	counter += 1
print("The number of characters is ", counter)

Output: The number of characters is 9

Iterating over a list of items

mylist = ["Delhi", "Paris", "Tokyo", "London"]

for city in mylist:
	print(city)

Output:

Delhi
Paris
Tokyo
London

In the above code, the city variable will hold the specific value of the list for every iteration. That is, for the first iteration, the value of city is ‘Delhi’, for the second iteration it will be ‘Paris’, and so on.

Difference between a while loop and a for loop in Python

The main difference between the two loops is that a for loop us used when the number of iterations is known, whereas the while loop is used when the number of iterations is unknown.

A loop is very essential concept in programming. If you have a large database, containing some information about the students or employees or whatever, and if you need to list them on a webpage you can simply loop through all the records!