Python: 루프

작성자

카테고리:

← 피드로
DEV Community · Mary Ngure · 2026-09-13 개발(SW)

One thing I’ve started noticing as I learn Python is that computers are really good at doing repetitive tasks.

Imagine being asked to print the numbers from 1 to 100 manually. Or process the scores of 50 students one by one.

That would be exhausting for a human.

For Python, however, repeating a task is exactly what loops are designed for.

Loops allow us to run a block of code multiple times without having to write the same code over and over again.

What is a Loop?

A loop tells Python:

“Keep doing this until we’ve finished.”

For example, instead of writing:

print(1)
print(2)
print(3)
print(4)
print(5)

Enter fullscreen mode Exit fullscreen mode

We can use a loop:

for number in range(1, 6):
    print(number)

Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5

Enter fullscreen mode Exit fullscreen mode

Much cleaner.

for Loops

A for loop is useful when we want to go through a sequence of items. It repeats KNOWN number of times, or over a collections of items.

That could be:

  • numbers
  • strings
  • lists
  • other collections of data

For example:

names = ["Mary", "John", "Ann"]

for name in names:
    print(name)

Enter fullscreen mode Exit fullscreen mode

Output:

Mary
John
Ann

Enter fullscreen mode Exit fullscreen mode

Python takes each item from the list, stores it temporarily in name, and runs the indented code.

Using range()

range() is particularly useful when working with numbers.

for number in range(1, 6):
    print(number)

Enter fullscreen mode Exit fullscreen mode

This prints numbers from 1 to 5.

One thing to remember is that the ending number is not included.
It stops before the number

So:

range(1, 6)

Enter fullscreen mode Exit fullscreen mode

means:

1, 2, 3, 4, 5

Enter fullscreen mode Exit fullscreen mode

while Loops

A while loop works a little differently.

Instead of going through a known sequence, it keeps running as long as a condition is true.

For example:

count = 1

while count <= 5:
    print(count)
    count += 1

Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5

Enter fullscreen mode Exit fullscreen mode

Here, Python keeps asking:

Is count <= 5?

As long as the answer is True, the loop continues.

The line:

count += 1

Enter fullscreen mode Exit fullscreen mode

is important because it changes the value of count.

Without it, the condition would remain true and we’d create an infinite loop.

When Should I Use for vs while?

A simple way I’m thinking about it is:

Use a for loop when you know what you’re going through.

for name in names:
    print(name)

Enter fullscreen mode Exit fullscreen mode

Use a while loop when you want to continue until a condition changes.

while savings < goal:
    savings += monthly_savings

Enter fullscreen mode Exit fullscreen mode

Both repeat code, but they are useful in different situations.

break: Stop the Loop

Sometimes we don’t want a loop to continue all the way through.

That’s where break comes in.

break immediately stops the loop.

For example:

for number in range(1, 11):
    if number == 6:
        break
    print(number)

Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5

Enter fullscreen mode Exit fullscreen mode

When Python reaches 6, the break statement stops the loop.

A practical example is asking a user to enter scores until they type "done":

scores = []

while True:
    score = input("Enter score or done: ")

    if score.lower() == "done":
        break

    scores.append(int(score))

print(scores)

Enter fullscreen mode Exit fullscreen mode

Here, while True creates a loop that keeps running, while break gives us a way to stop it.

continue: Skip an Iteration

continue is different from break.

Instead of stopping the loop completely, continue tells Python:

“Skip this one and move to the next iteration.”

For example, suppose we want to print numbers from 1 to 5 but skip 3:

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Enter fullscreen mode Exit fullscreen mode

Output:

1
2
4
5

Enter fullscreen mode Exit fullscreen mode

The loop didn’t stop. It simply skipped the iteration where number was 3.

So a useful way to remember them is:

break → Stop the loop

continue → Skip this iteration

enumerate(): Get the Position and the Value

Another useful concept I’ve come across is enumerate().

When looping through a list, sometimes we want both:

  1. The item
  2. Its position in the list

For example:

names = ["Mary", "John", "Ann"]

for index, name in enumerate(names):
    print(index, name)

Enter fullscreen mode Exit fullscreen mode

Output:

0 Mary
1 John
2 Ann

Enter fullscreen mode Exit fullscreen mode

By default, enumerate() starts counting from 0.

We can change that by specifying start=1:

names = ["Mary", "John", "Ann"]

for number, name in enumerate(names, start=1):
    print(number, name)

Enter fullscreen mode Exit fullscreen mode

Output:

1 Mary
2 John
3 Ann

Enter fullscreen mode Exit fullscreen mode

This is especially useful when creating reports, rankings, menus, or numbered lists.

Practical Example: Student Scores

Let’s bring these concepts together.

Suppose we have a list of student scores and want to generate a simple report:

scores = [85, 72, 64, 91, 48]

for number, score in enumerate(scores, start=1):
    if score >= 50:
        result = "Pass"
    else:
        result = "Fail"

    print(f"Student {number}: {score} - {result}")

Enter fullscreen mode Exit fullscreen mode

Output:

Student 1: 85 - Pass
Student 2: 72 - Pass
Student 3: 64 - Pass
Student 4: 91 - Pass
Student 5: 48 - Fail

Enter fullscreen mode Exit fullscreen mode

Here we’re combining loops, enumerate(), conditionals, and f-strings in one small program.

Practical Example: Savings Goal

A while loop can also be useful for something like tracking savings.

goal = float(input("What is your savings goal? "))
monthly_savings = float(input("How much can you save per month? "))

total = 0
months = 0

while total < goal:
    total += monthly_savings
    months += 1

print(f"It will take you {months} months to reach your goal.")
print(f"You will have saved {total:.2f}.")

Enter fullscreen mode Exit fullscreen mode

The loop continues adding the monthly savings until the total reaches the goal.

This is a good example of why while loops are useful: we don’t necessarily know how many times the loop needs to run beforehand.

A Simple Mental Model

I’m finding it helpful to think about loops like this:

Start → Repeat → Check → Repeat or Stop

For a for loop:

Take an item → Do something → Take the next item → Continue

Enter fullscreen mode Exit fullscreen mode

For a while loop:

Check condition → Do something → Check again → Stop when false

Enter fullscreen mode Exit fullscreen mode

And then we have:

break    → Stop completely
continue → Skip this round
enumerate() → Get the position + the item

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

The main things I’m taking away from loops are:

  • for loops are useful for going through sequences of items.
  • while loops repeat code while a condition remains true.
  • break stops a loop completely.
  • continue skips the current iteration.
  • enumerate() gives us both the position and the item when looping through a sequence.
  • Loops become even more powerful when combined with conditionals, lists, and functions.

The more I practice loops, the more I see how much repetitive work Python can handle for me. Instead of writing the same instructions repeatedly, I can define the process once and let the computer do the repetition.

원문에서 계속 ↗

추출 본문 · 출처: dev.to · https://dev.to/maryngure/python-loops-29k8