Python Loops

Python Loops Tutorial

Introduction:

Loops are one of the most important concepts in Python. They allow you to execute a block of code repeatedly, which makes tasks like iterating through lists, performing calculations, or automating repetitive operations much easier

1). What Are Loops in Python?

A loop in Python is used to execute a set of statements multiple times until a certain condition is met. This helps avoid writing the same code over and over again. There are mainly two types of loops in Python:

  • for loop
  • while loop

2). Using the range() Function

The range() function is commonly used in loops to generate a sequence of numbers. It’s very useful when you want to repeat an action a specific number of times.

Syntax:

range(start, stop, step)

  • start – the starting number (default is 0)
  • stop – the number at which the range ends (not included)
  • step – the difference between each number (default is 1)

3). The for Loop

A for loop is used when you know how many times you want to execute a block of code. It’s great for iterating through sequences like lists, tuples, or strings.


4). Nested for Loops

A nested loop means having one loop inside another. This is often used for working with multidimensional data, like matrices or tables.


5). The while Loop

A while loop continues to run as long as a given condition is True. You use it when you don’t know how many times you need to repeat a block of code.

If the condition never becomes False, the loop runs forever (an infinite loop). To avoid that, always make sure the condition changes within the loop.


6). The break Statement

The break statement is used to stop a loop immediately, even if the loop’s condition is still True.


7). The continue Statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next one


8). Combining break and continue

You can use both break and continue in the same loop to control its flow precisely.


9). Real-Life Example: Password Check

Here’s a simple example that uses both a while loop and break:


10). Summary Table

ConceptDescriptionExample
for loopRuns a block of code a set number of timesfor i in range(5): print(i)
while loopRuns as long as a condition is truewhile x < 10:
range()Generates a sequence of numbersrange(1, 10, 2)
breakStops the loopif i == 5: break
continueSkips current iterationif i % 2 == 0: continue
Nested loopA loop inside anotherfor i in range(3): for j in range(3): …