Learning Python Loops with Easy Examples

A beginner-friendly guide to understanding and using loops in Python with simple examples.

Loops are fundamental concepts in programming that allow you to repeat a block of code multiple times. They help you automate repetitive tasks without having to write the same code over and over. In Python, there are two main types of loops: for loops and while loops.

Let's start with the for loop. It is used when you know the number of times you want to repeat an action or when you want to iterate over a collection like a list or a range of numbers.

python
for i in range(5):
    print("Number", i)

In this example, the for loop will print numbers from 0 to 4. The range(5) function creates a sequence of numbers from 0 up to (but not including) 5. The variable i takes each value in the sequence one by one. Note the indentation—Python uses indentation to group code inside loops.

Next, the while loop repeats as long as a specified condition is true. This type of loop is useful when you don't know in advance how many times you need to repeat the code, and the repetition depends on a condition.

python
count = 0
while count < 5:
    print("Count is", count)
    count += 1

Here, the while loop continues to run as long as count is less than 5. Inside the loop, we print the current count and then increase it by 1 using count += 1. If you forget to increase count inside the loop, the condition will always be true, causing an infinite loop. This means your program will keep running forever, which is a common mistake. To fix it, always make sure the condition will eventually become false by updating variables appropriately.

Understanding loops will greatly simplify tasks where you need repetition, such as processing items in lists, performing calculations repeatedly, or handling user input until a condition is met. Practice writing different types of loops and pay careful attention to the loop conditions and increments to avoid common errors.