Loops in Python Programming – For and While

In Python, a loop is a programming construct that allows you to repeat a block of code multiple times. There are two types of loops in Python: for loop and while loop.

For loop

A for loop is used to iterate over a sequence (e.g., a list, tuple, dictionary, or string) and execute a block of code for each item in the sequence. Here’s the basic syntax of a for loop in Python:

for item in sequence:
    # code to be executed

Here’s an example that uses a for loop to print the numbers from 1 to 5:

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

Output:

1
2
3
4
5

In the example above, the range() function generates a sequence of numbers from 1 to 5 (inclusive) and the for loop iterates over each number in the sequence and prints it.

While loop

A while loop is used to execute a block of code repeatedly as long as a certain condition is true. Here’s the basic syntax of a while loop in Python:

while condition:
    # code to be executed

Here’s an example that uses a while loop to print the numbers from 1 to 5:

i = 1
while i <= 5:
    print(i)
    i += 1

Output:

1
2
3
4
5

In the example above, the while loop iterates over the numbers from 1 to 5 as long as i is less than or equal to 5. The loop starts with i equal to 1, prints the value of i, increments i by 1, and repeats the process until i becomes 6, at which point the loop stops.

Loops are a fundamental building block of programming, and they allow you to write more efficient and concise code by automating repetitive tasks.

Here are some more examples of loops in Python:

Example 1: Printing the elements of a list using a for loop

fruits = ["apple", "banana", "orange", "grape"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
orange
grape

In the example above, the for loop iterates over each item in the fruits list and prints it.

Example 2: Calculating the sum of a list using a for loop

numbers = [1, 2, 3, 4, 5]
sum = 0
for number in numbers:
    sum += number
print("The sum is:", sum)

Output:

The sum is: 15

In the example above, the for loop iterates over each item in the numbers list and adds it to the sum variable.

Example 3: Printing the numbers from 1 to 10 using a while loop

i = 1
while i <= 10:
    print(i)
    i += 1

Output:

1
2
3
4
5
6
7
8
9
10

In the example above, the while loop iterates over the numbers from 1 to 10 as long as i is less than or equal to 10. The loop starts with i equal to 1, prints the value of i, increments i by 1, and repeats the process until i becomes 11, at which point the loop stops.

Leave a Comment