liveBook · Manning

Nested loop

As explained in Get Programming: Learn to code with Python

A nested loop is a loop placed inside another loop so that its execution occurs within each iteration of the outer loop.

A nested loop places one loop inside another. The outer loop handles each larger item; the inner loop examines the smaller items belonging to it. In the Scrabble word-matching problem, the outer loop checks each valid word, while the inner loop checks each letter in that word. section 19.1 section 19.2

Checking words against tiles

For each word, begin with all available tiles. Check its letters one at a time. If a letter is missing, stop checking that word and continue with the next one. If a letter is found, remove it from the remaining tiles so repeated letters are handled correctly. After the inner loop, add the word only if every letter was matched. section 19.2

for word in valid_words:
    for letter in word:
        if letter not in tiles:
            stop looking at remaining letters and go to next word
        else:
            remove letter from tiles (in case of duplicates)
    if all letters in valid word found in tiles:
        add word to found_words

Trace the outer word loop and inner letter loop directly, including the early exit for a missing letter and the handling of duplicate tiles. section 19.1 section 19.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains outer and inner responsibilities, early exit, duplicate handling, remaining state, and the final completion check.
Examples
Demonstrates word candidates, individual letters, tile removal, duplicate letters, and words such as art, hue, and color.
What it assumes
Assumes familiarity with basic loops and variables while teaching the nested structure through a concrete word-matching task.
What you can do after
Build it from scratch by translating a two-level checking process into pseudocode and executable loop logic.
How it connects
Connects nested loops with loops, pseudocode, conditionals, variables, and breaking out of iteration.

Also explained in

Compare how 3 books explain nested loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.