Saturday, January 18, 2025
HomeProgrammingWhat is Loops in Python?

What is Loops in Python?

In Python, loops are used to execute a block of code repeatedly as long as a condition is true. There are two primary types of loops in Python:

1. for loop:

The for loop iterates over a sequence (such as a list, tuple, string, or range) and executes a block of code for each item in the sequence.

Syntax:

for variable in sequence:
    # code block

Example:

for i in range(5):
    print(i)

This will print:

0
1
2
3
4

In this case, the for loop iterates over the numbers from 0 to 4 (generated by range(5)) and prints each number.

See also  Software development life cycle (SDLC)

2. while loop:

The while loop executes a block of code as long as a specified condition is true. It keeps checking the condition before each iteration.

Syntax:

while condition:
    # code block

Example:

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

This will also print:

0
1
2
3
4

In this example, the loop continues to run as long as the condition i < 5 remains true. The variable i is incremented by 1 each time to avoid an infinite loop.

See also  What is the difference between 'Precision' and 'Accuracy'?

Key Concepts:

  • break: Exits the loop prematurely.
  • continue: Skips the current iteration and moves to the next iteration.
  • else: The else block is optional and will execute when the loop completes normally (without hitting a break).

Example with else and break:

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("Loop completed")  # This won't be printed because the loop was broken

Output:

0
1
2

Loops are essential for repetitive tasks in Python and are a core part of the language’s control flow.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x