Wed 08 April 2026

Nested Loops Visualization Tool

Posted by Al Sweigart in misc   

Nested loops are a concept that beginner programmers sometimes have trouble with, so I created a nested loop visualization tool using Claude Opus 4.6 to demonstrate the behavior of nested loops using a clock interface. The loops are represented by clock hands and just as a seconds clock hand must make a full loop before the minutes hand increments by one, the innermost loops must complete a full loop to increment the outer loops.

The tool works offline and doesn't have any dependencies, so you can download the .html file and use it anywhere you want. The prompt I used was as follows (and is in a comment in the source HTML): "Create a JavaScript animation that demonstrates nested Python for loops using a clock visualization. The visualization starts with "for i in range(10)" and "for j in range(5)" (though the user can add additional for loops, or change the variable names and the single integer argument to the range() function) and the clock has two hands, i and j, which start pointing to 0 at the top of the clock. There are separate sets of number labels for each clock hand. In my example, the i clock hand has a set of labels around the clock that start at 0 and go up to 9, while the j clock hand has another set of labels around the clock starting at 0 and going up to 4. Adding more for loops adds more clock hands and labels. Have the innermost set of labels reflect the innermost for loop, so the i loop's labels would be outside (further away from the clock center) than the j loop's labels. There is a "Next" button which moves the innermost loop by 1 and shows the innermost clock hand moving clockwise by one increment. The numbers on the clock always being with 0 at the top (we only support the 1-argument version of the range() function call) and go to the last argument. There is also a display of the current variable values, and also a display of all of the variable values up to the current values (like if print("i =", i, ", j =", j) were the code inside all of the loops). There's also a "Prev" button to go back, and a "Reset" button to reset all loop variables back to 0. This animation teaches students how nested for loops work, and how the innermost loop completely finishes for a single increment in the outer loop. Make this a standalone .html file that does not have any external packages or libraries. It should work offline. Make the visual style match the dark mode or light mode setting of the browser."


Check out other books by Al Sweigart, free online or available for purchase:

...and other books as well! Or register for the online video course. You can also donate to or support the author directly.