Home » Data Science » Python » Python Loop

Newly Updated Posts

Python Loop

Explore our Python tutorials for beginners In this Tutorial , we will learn looping concepts in Python.

In Python, loops are used to repeat a specific block of code multiple times. They allow you to iterate over a sequence of elements or execute a block of code until a specific condition is met. Python provides two types of loops: the for loop and the while loop.

1. For Loop: The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. It has the following syntax:

for variable in sequence:
    # code block

Here, variable is a variable that takes on the value of each element in the sequence during each iteration. The code block under the loop is executed for each element in the sequence.

Example 1: Printing each element of a list using a for loop:

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

Example 2: Calculating the sum of numbers in a range using a for loop:

total = 0

for num in range(1, 6):

total += num

print(total)

2. While Loop: The while loop repeatedly executes a block of code as long as a given condition is true. It has the following syntax:

while condition:
    # code block

The code block is executed as long as the condition remains true. If the condition becomes false, the loop is terminated, and the program continues with the next statement after the loop.

Example 1: Printing numbers from 1 to 5 using a while loop:

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

Example 2: Finding the factorial of a number using a while loop:

num = 5
factorial = 1
while num > 0:
    factorial *= num
    num -= 1
print(factorial)

It’s important to ensure that the loop condition eventually becomes false; otherwise, the loop will continue indefinitely, resulting in an infinite loop.

Both for and while loops can be controlled using statements like break (to exit the loop) and continue (to skip the current iteration and move to the next).