My Notes

Python Loops - The Complete Breakdown

Updated 6/28/20268 min readDownload PDFEdit

Python Loops — The Complete Breakdown

So what even is a loop?

Imagine you have a list of 1000 usernames and you want to print every single one. You could write print(usernames[0]), print(usernames[1]), print(usernames[2])... all the way to 999. That's insane. Nobody does that.

A loop says: "take this block of code, and run it repeatedly — either for every item in something, or until some condition stops being true." One clean block of code, runs as many times as you need.

Python has two main loops: for and while. Plus a few bonus tools that make loops even more powerful. Let's go through all of them.


The for loop — when you know what you're looping over

A for loop goes through a collection — a list, a string, a range of numbers — one item at a time. For every item, it runs the indented code block once.

skills = ["python", "security", "hacking", "ctf"]

for skill in skills:
    print(skill)

Output:

python
security
hacking
ctf

Read it like English: "for each skill in skills, print that skill." That's literally what it does.

The variable name after for is yours to choose — skill, item, x, anything. It temporarily holds the current item on each pass through the loop.

for x in skills:
    print(x)

Same result, different variable name. The name doesn't matter — consistency and clarity do.


Looping over a range of numbers

range() generates a sequence of numbers. You don't need a list — just tell it where to start and stop.

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

Output:

0
1
2
3
4

range(5) gives you 0 through 4 — five numbers, but stops before 5. This trips people up. Remember: the end number is always excluded.

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

Output:

1
2
3
4
5

range(start, stop) — starts at 1, stops before 6. Gives you 1 through 5.

for i in range(0, 10, 2):
    print(i)

Output:

0
2
4
6
8

range(start, stop, step) — the third argument is the step. Here it goes up by 2 each time.

Counting down:

for i in range(5, 0, -1):
    print(i)

Output:

5
4
3
2
1

Step of -1 counts backwards.


Looping over a string

Strings are sequences too — you can loop over each character.

word = "python"

for letter in word:
    print(letter)

Output:

p
y
t
h
o
n

Looping with index — enumerate()

Sometimes you need both the item and its position. enumerate() gives you both.

skills = ["python", "security", "hacking", "ctf"]

for index, skill in enumerate(skills):
    print(f"{index}: {skill}")

Output:

0: python
1: security
2: hacking
3: ctf

Start the index from 1 instead of 0:

for index, skill in enumerate(skills, start=1):
    print(f"{index}. {skill}")

Output:

1. python
2. security
3. hacking
4. ctf

Looping over two lists at once — zip()

zip() pairs up items from two lists, one at a time.

names  = ["Alice", "Bob", "Kalyan"]
scores = [95, 87, 100]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

Output:

Alice: 95
Bob: 87
Kalyan: 100

The while loop — when you loop until something changes

A while loop doesn't care about a list or a range. It just keeps running as long as a condition is True. The moment the condition becomes False, it stops.

count = 0

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

Output:

0
1
2
3
4

count += 1 is shorthand for count = count + 1. Every loop, count goes up by 1. When count hits 5, the condition count < 5 becomes False and the loop ends.

The classic beginner trap — forget to update the variable and you get an infinite loop:

count = 0

while count < 5:
    print(count)
    # forgot count += 1 — this runs forever

If you ever run code that doesn't stop, hit Ctrl + C to kill it.


While loop with user input

This is where while really shines — looping until the user does something.

password = ""

while password != "secret":
    password = input("Enter the password: ")

print("Access granted.")

This keeps asking until the user types "secret". You couldn't do this with a for loop because you don't know how many attempts the user will need upfront.


While True — loop forever until you break out

while True:
    answer = input("Type 'quit' to exit: ")
    if answer == "quit":
        break
    print(f"You typed: {answer}")

while True runs forever on purpose. The only way out is break, which exits the loop immediately. This pattern is everywhere in real Python programs — menus, servers, games.


Loop control — break, continue, pass

These three keywords give you fine control over what happens mid-loop.

break — exit the loop immediately

scores = [72, 85, 91, 100, 60]

for score in scores:
    if score == 100:
        print("Perfect score found!")
        break
    print(f"Checking: {score}")

Output:

Checking: 72
Checking: 85
Checking: 91
Perfect score found!

The moment it finds 100, it breaks out. The 60 never even gets checked.


continue — skip this iteration, keep going

scores = [72, 85, -1, 91, -1, 100]

for score in scores:
    if score == -1:
        continue
    print(f"Score: {score}")

Output:

Score: 72
Score: 85
Score: 91
Score: 100

continue says "skip this one and move to the next." The -1 values got skipped, but the loop kept running.


pass — do nothing, placeholder

for score in scores:
    if score == -1:
        pass   # handle invalid scores later
    else:
        print(f"Score: {score}")

pass is literally a no-op. Python requires something in an indented block — if you have nothing to put there yet, pass holds the spot. Useful when you're sketching out code structure before filling it in.


The bonus — list comprehensions

This is Python's slickest feature for loops. Instead of writing a full for loop to build a list, you can do it in one line.

The long way:

scores = [72, 85, 91, 100]
doubled = []

for score in scores:
    doubled.append(score * 2)

print(doubled)

Output:

[144, 170, 182, 200]

The one-liner with list comprehension:

scores = [72, 85, 91, 100]
doubled = [score * 2 for score in scores]

print(doubled)

Output:

[144, 170, 182, 200]

Same result, one line. The pattern is: [expression for item in collection].

You can add a condition too:

scores = [72, 85, 91, 100, 55, 60]
passing = [score for score in scores if score >= 70]

print(passing)

Output:

[72, 85, 91, 100]

Pattern: [expression for item in collection if condition]. Only items that pass the condition make it into the new list.


Nested loops — a loop inside a loop

Sometimes you need to loop over something that itself contains multiple things — like a grid, a table, or a list of lists.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for item in row:
        print(item, end=" ")
    print()

Output:

1 2 3 
4 5 6 
7 8 9 

The outer loop goes through each row. The inner loop goes through each item in that row. For every one pass of the outer loop, the inner loop runs completely.

end=" " in print() replaces the default newline with a space, so items print on the same line. The empty print() after the inner loop adds the line break between rows.


All the scenarios — which loop to use when

You have a list and want to do something with each item → for

for url in target_urls:
    scan(url)

You want to repeat something N times → for with range()

for i in range(10):
    send_ping()

You need both the item and its position → for with enumerate()

for i, item in enumerate(results):
    print(f"Result {i+1}: {item}")

You loop until a condition changes — user input, retry logic, server polling → while

while not connected:
    attempt_connection()

You need to run forever until something specific happens → while True with break

while True:
    data = read_packet()
    if data == "EXIT":
        break
    process(data)

You want to build a new list from an existing one → list comprehension

open_ports = [p for p in ports if is_open(p)]

You want to skip certain items mid-loop → continue

for line in log_file:
    if line.startswith("#"):
        continue
    parse(line)

The decision table

SituationUse
Loop over a list, string, or rangefor
Loop N times exactlyfor i in range(N)
Need index + valuefor i, v in enumerate(...)
Loop two lists togetherfor a, b in zip(...)
Loop until condition changeswhile condition
Loop forever, break manuallywhile True + break
Build a new list from a looplist comprehension
Skip some itemscontinue
Exit loop earlybreak

The one-line summary

for loops over a known collection. while loops until a condition flips. break exits early, continue skips an iteration, and list comprehensions collapse a loop into one clean line. Master these five and you can handle almost any repetition problem Python throws at you.