Loops in Python

You have learned how to change the flow of your code with conditionals like if, else and elif. There is another way of controlling the flow of a program. We call it a loop. There are two loops in Python, for loops and while loops.

Imagine that your dog is sick and the doctor wants you to sing a song for her every 30 mins. You will have to keep an alarm clock on at 30 mins intervals and wake up even when you are sleeping. After a few songs, you will get tired and start lagging.

However, this is the reason why we have computers. Unlike humans, computers are built because they can do or perform repeated tasks for as long as they are on.

Assuming your vet advices that you sing the song to the dog 10 times before sunset, you will need to set an alarm and tell the alarm to repeat at 30 mins intervals in 10 instances.

The alarm is a program and it will sing the song at 30 mins intervals, and it will stop once it rings the 10th time.

That is how a Python for loop works. You write a code for the loop to run (ring an alarm) and ask it to run it for how many times (10 times) until the loop has repeated over every ring you stated in the setting. For loops allow you to repeat the same operation in a set number of repetitions.

If you want to write a program that performs a repeated task over a period of time, you will use a loop. Loops let you do the same thing over and over again in your code.

These statements tell the computer to do the same thing over and over again until certain conditions are met.

For example, when you want to code a program that has to be written again and again, your script can become very long if it has to be done a lot. Loops help us cut down on this repetition of code. With loops, we can cut those hundred lines of code down to a few. If you want to print the text “Hello, World!” 10 times, instead of writing a print statement 10 times, you can use loops by telling how many times you need to do it.

print ("Hello world")
print ("Hello world")

print ("Hello world")

print ("Hello world")

print ("Hello world")

print ("Hello world")

print ("Hello world")

print ("Hello world")

print ("Hello world")

print ("Hello world")

Loop Types

In Python programming, there are three types of loops:

  •     while loop
  •     for loop
  •     nested loops

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials