DEV Community

Raj
Raj

Posted on

What is looping in python

What is Looping in Python?

Looping in Python means executing the same block of code repeatedly until a particular condition is met or a given sequence is completed.

In programming sometimes we need to perform the same task multiple times. Instead of writing the same code again and again we can use loops to repeat the task automatically. This makes the code shorter easier to understand and reduces unnecessary repetition.

For example if we want to print "Hello" five times we don't need to write five separate print statements. We can simply use a loop to do it.

Python mainly provides two types of loops:
For Loop and While Loop.

1. For Loop

A for loop is used when we want to repeat something a certain number of times or work with items in a sequence.
For example if we want to print numbers from 1 to 5 we can use a for loop.


python
for i in range(1, 6):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Here, range(1, 6) generates numbers from 1 to 5. The variable i takes each number one by one, and the print statement displays it.

2. While Loop

A while loop works a little differently. It keeps repeating the code as long as the given condition is True.

Example:


python
i = 1

while i <= 5:
    print(i)
    i = i + 1
Enter fullscreen mode Exit fullscreen mode

We start with the value 1. The loop checks whether the value is less than or equal to 5. If the condition is True it prints the number and increases the value by 1. This continues until the condition becomes False.

3. Break Statement

Sometimes, we may want to stop a loop before it finishes. For that Python provides the break statement.

Example:

python
for i in range(1, 6):
    if i == 3:
        break
    print(i)

Enter fullscreen mode Exit fullscreen mode

The loop stops when the value reaches 3. So it prints only 1 and 2.

  1. Continue Statement

The continue statement is used when we want to skip a particular iteration and move to the next one.

For example:

python
for i in range(1, 6):
    if i == 3:
        continue
    print(i)
Enter fullscreen mode Exit fullscreen mode

When the value becomes 3 it skips that number and continues with the remaining numbers.
Loops are an important part of Python programming because they help us repeat tasks without writing the same code multiple times. A for loop is useful when working with a sequence or a fixed number of repetitions while a while loop is useful when repetition depends on a condition.

Top comments (0)