Skip to main content

Loops

In programming, we use Loops to repeat actions automatically without writing the same lines of code over and over again.


1. Life Without Loops vs With Loops

Imagine you want to print "Hello!" 5 times on the screen.

Without Loops:

You have to manually copy and paste the same print statement 5 times:

print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")

With Loops:

You write the instruction once, and tell Python to repeat it:

for i in range(5):
print("Hello!")

Both codes do the exact same thing, but the loop is much cleaner and easier to scale! If you wanted to print it 100 times, you would just change range(5) to range(100).


2. What is i in the Loop?

In the code for i in range(5):, beginners often ask: "Where did i come from? Is it a Python keyword?"

The Answer: No, i is just a standard variable name.

  • It stands for "iteration" (which means "repeat" or "round") or "index".
  • Each time the loop repeats a round, Python automatically stores the current number inside i.
  • You can name this variable anything (like for x in range(5):), but programmers standardly use i as a shortcut.

Let's print i to see what Python stores inside it:

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

Output:

0
1
2
3
4

Why did it start at 0? In Python (and most programming languages), counting starts at 0, not 1. This is called Zero-Indexing. So, range(5) gives you 5 numbers: 0, 1, 2, 3, and 4.


3. Counting differently with range()

You can customize how the range() function counts by giving it different numbers:

Count from a starting point: range(start, stop)

The loop will start at start, but stops right before it reaches stop.

# Count from 1 to 5 (Stops before 6!)
for i in range(1, 6):
print(i)

# Output: 1, 2, 3, 4, 5

Skip numbers: range(start, stop, step)

The third number tells Python how many numbers to skip in each round.

# Count by 2s (Even numbers from 2 up to 10)
for i in range(2, 11, 2):
print(i)

# Output: 2, 4, 6, 8, 10

Countdown: range(start, stop, negative_step)

You can count backwards by using a negative step value.

# Countdown from 5 down to 1
for i in range(5, 0, -1):
print(i)

# Output: 5, 4, 3, 2, 1

4. Looping through text (Strings)

Since strings are just sequences of letters, you can use a for loop to inspect each letter one by one:

name = "Python"

for letter in name:
print(letter)

Output:

P
y
t
h
o
n

Here, Python stores the first letter "P" in letter, prints it, then moves to "y", prints it, and repeats until the end of the word!


What's Next?

A for loop is perfect when you know exactly how many times to repeat. But what if you want to repeat code based on a condition (like playing a game while you still have lives)? Let's learn about while loops in the next lesson!