What are loops?

In programming, loops are used to repeat a set of instructions multiple times. They allow you to avoid writing the same code over and over again, making your programs more efficient and easier to maintain. There are two types of loops in Python: for loops and while loops.

The for loop

A for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. The basic syntax of a for loop in Python is as follows:

for item in sequence:
    # code to execute for each item

Here, item is a variable that takes on the value of each item in the sequence, one at a time. The code to be executed for each item should be indented to indicate that it is part of the loop.

The while loop

A while loop is used to execute a block of code repeatedly as long as a certain condition is true. The basic syntax of a while loop in Python is as follows:

while condition:
    # code to execute while condition is true

Here, condition is a boolean expression that determines whether the loop should continue executing. The code to be executed while the condition is true should be indented to indicate that it is part of the loop.

Sample Code Snippets

Now that we have a basic understanding of loops, let's take a look at some code examples.

Easy

Code: Print the numbers from 1 to 5 using a for loop.

for num in range(1, 6):
    print(num)

Output:

1
2
3
4
5

Description: Here, we are using the range() function to generate a sequence of numbers from 1 to 5. The for loop then iterates over each number in the sequence and prints it to the console.

Medium

Code: Calculate the sum of the first 10 natural numbers using a while loop.