basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Loops in Python: for over anything, while until a condition, break

    for walks through a collection — lines of text, characters, numbers from range — and runs a block for each. while repeats while a condition is true. break leaves the loop early, continue skips a step. Count the errors in a log, and make retry pauses that double each time.

    New hereThe for loopThe while loop and break

    What you’ll get

    How many errors a backup log has, and which:

    # log_errors.py
    log = """2026-10-21 10:00:01 INFO  backup started
    2026-10-21 10:04:12 ERROR disk /dev/sdb not found
    2026-10-21 10:04:13 WARNING retry in 5 s
    2026-10-21 10:04:18 ERROR disk /dev/sdb not found
    2026-10-21 10:05:00 INFO  backup finished"""
    
    errors = 0
    for line in log.splitlines():
        if "ERROR" in line:
            errors += 1
            print(line)
    print("Errors:", errors)
    python log_errors.py
    # 2026-10-21 10:04:12 ERROR disk /dev/sdb not found
    # 2026-10-21 10:04:18 ERROR disk /dev/sdb not found
    # Errors: 2

    splitlines() cuts the text into lines, and for takes them one at a time into the name line. errors += 1 is short for errors = errors + 1. The last print has no indent — it runs after the loop, once. Reading the log from a file comes in the “Files and paths” chapter; the loop stays the same.

    What will it print?
    for i in range(3):
        print(i, end=" ")
    What will it print?
    Answer:
    0 1 2

    range(3) is three numbers starting from zero: 0, 1, 2. The end isn’t included, as in the slice [0:3]. end=" " makes print put a space instead of a line break.

    How it works: for takes one at a time

    for name in collection: takes the next value out of the collection, puts it into the name and runs the block; when the values run out, the loop ends. A collection can be anything you can walk through:

    Over what Example What goes into the name
    lines of text for line in log.splitlines(): one line after another
    characters of a string for ch in "ssh": "s", "s", "h"
    numbers for n in range(1, 101): 1, 2, … 100
    a file, a list, a dictionary the “Files and paths”, “Lists and tuples”, “Dictionaries and sets” chapters lines of the file, items, keys

    range gives numbers in order: range(5) is 0 through 4, range(1, 10, 3) is 1, 4, 7, range(5, 0, -1) counts down from 5 to 1. The end isn’t included.

    When you need a line’s number along with the line, use enumerate: for n, line in enumerate(log.splitlines(), start=1):. It hands out “number and value” pairs, and for unpacks each pair into two names; pairs are covered in detail in the “Lists and tuples” chapter.

    while — as long as the condition holds

    while doesn’t know in advance how many steps there will be: it checks the condition before each one. An example — a pause between retries that doubles each time, so you don’t hammer a server that’s down:

    wait = 1
    while wait < 60:
        print(f"retry in {wait} s")
        wait *= 2
    retry in 1 s
    retry in 2 s
    retry in 4 s
    retry in 8 s
    retry in 16 s
    retry in 32 s

    wait *= 2 is the same as wait = wait * 2. Without this line wait is always 1, the condition is always true, and the loop never ends. Ctrl+C stops such a script.

    break and continue

    break leaves the loop right away; continue drops the current step and goes on to the next:

    for n, line in enumerate(log.splitlines(), start=1):
        if "ERROR" in line:
            print("first error on line", n)    # first error on line 2
            break
    
    for line in log.splitlines():
        if "INFO" in line:
            continue
        print(line[20:])    # without the date: ERROR disk /dev/sdb not found…

    line[20:] is a slice from the Strings chapter: the date and time take the first 20 characters.

    A sum of numbers is the same counter as for the errors: start at zero before the loop, add in the loop.

    total = 0
    for n in range(1, 101):
        total += n
    print(total)    # 5050

    Take it further

    Powers of two up to 2¹⁶, every fourth: 1, 16, 256…

    range with a step of 4 from 0 to 16 inclusive; in the f-string, , separates thousands.

    for p in range(0, 17, 4):
        print(f"2**{p} = {2 ** p:,}")
    # 2**0 = 1
    # 2**4 = 16
    # 2**8 = 256
    # 2**12 = 4,096
    # 2**16 = 65,536
    Count errors and warnings in the log separately

    Two counters before the loop; in the loop, if for ERROR and elif for WARNING.

    errors = 0
    warnings = 0
    for line in log.splitlines():
        if "ERROR" in line:
            errors += 1
        elif "WARNING" in line:
            warnings += 1
    print("Errors:", errors, "warnings:", warnings)
    # Errors: 2 warnings: 1
    Keep asking for a password until it’s longer than 11 characters

    while with a condition on length; before the loop, an empty string so the condition has something to compare.

    password = ""
    while len(password) < 12:
        password = input("Password, 12+ characters: ")
    print("accepted")

    If it doesn’t work

    The script never ends, and the terminal doesn’t respond

    Cause
    The while condition is always true: nothing inside the loop changes what it checks.
    Fix
    Ctrl+C stops the script with KeyboardInterrupt. The loop needs a line that moves toward the exit: wait *= 2, tries += 1.

    range(1, 10) didn’t reach 10

    Cause
    The end isn’t included in range, just as in a slice: range(1, 10) is 1 through 9.
    Fix
    For up to and including 10, use range(1, 11).

    The total prints on every step instead of once

    Cause
    The print is indented inside the loop.
    Fix
    Move the print left, to the level of for: a line without the indent runs after the loop.

    TypeError: 'int' object is not iterable

    Cause
    for i in 5: — you can’t walk through a number; you need a collection.
    Fix
    Five repetitions: for i in range(5):.

    IndentationError: expected an indented block after 'while' statement on line 2

    Cause
    The loop body isn’t indented.
    Fix
    Indent the body 4 spaces under the line with the colon.