DEV Community

still-purrfect
still-purrfect

Posted on

Loops in Programming: How to Make Your Code Repeat Without Stress

Have you ever written the same code again and again and thought there must be a better way?
That’s exactly what loops solve.
So far, we’ve learned how to store data, make decisions using if statements, and work with operators.
But what if we want to repeat something multiple times?
Instead of writing the same code over and over, we use loops.
Loops allow your program to repeat a block of code as many times as needed.

🔹 1. For Loop

A for loop is used when you know how many times you want to repeat something.

for i in range(5):
    print("Hello")
Enter fullscreen mode Exit fullscreen mode

This prints “Hello” 5 times.

🔹 2. While Loop

A while loop keeps running as long as a condition is true.

x = 1

while x <= 5:
    print(x)
    x = x + 1
Enter fullscreen mode Exit fullscreen mode

This prints numbers from 1 to 5.

💡 Why Loops Matter

Loops save time and reduce repetition.
Without loops, you repeat code manually.
With loops, one line can do the work of many.
They are one of the most important tools in programming because they make your code efficient and scalable.

🌱 Challenge

Write a program that:

  • Prints numbers from 1 to 10
  • Then prints “Python is fun” 5 times

Try to do it using both:

  • a for loop
  • a while loop

Next, we’ll explore strings, where you learn how to work with text in a deeper and more practical way.

Top comments (0)