DEV Community

Vishwa K
Vishwa K

Posted on

Loops in python

What Is a Loop?
Imagine you want to print numbers from 1 to 10. Without a loop, you'd write:
print(1)
print(2)
print(3)

... all the way to 10

With a loop, you write it once and let Python do the work
The while Loop
A while loop keeps running as long as a condition is True.
Syntax
python while condition:
# code to repeat
Example 1 — Print 1 to 19
python
i = 1
while i < 20:
print(i)
i += 1
Output:
1
2
3
...
19
Breaking it down:

i = 1 → we start counting from 1
i < 20 → keep going as long as i is less than 20
i += 1 → increase i by 1 each time (so we don't loop forever!)
The for Loop
The for loop is Python's preferred way to repeat something a fixed number of times.
Syntax
python
for variable in sequence:
# code to repeat
Example — Print 1 to 10
python
for i in range(1, 11):
print(i)
Output:
1
2
3
...
10
range(1, 11) generates numbers from 1 up to (but not including) 11. So we get 1 through 10.
Summary
A loop repeats code automatically.
A while loop runs as long as its condition is True.
A for loop is ideal when you know how many times to repeat.
Use range() with for loops to generate number sequences.
Wrap loops in functions to make them reusable.

Top comments (0)