Loops Within Loops
Loops within loops, also known as nested loops, occur frequently in programming. For instance, here’s a program that prints the times tables up to 10:
# timestable.py for row in range(1, 10): for col in range(1, 10): prod = row * col if prod < 10: print(' ', end = '') print(row * col, ' ', end = '') print()
Look carefully at the indentation of the code in this program: It’s how you tell what statements belong to what blocks. The final print() statement lines up with the second for, meaning it is part of the outer for-loop (but not the inner).
Note that the statement if prod < 10 is used to make the output look neatly formatted. Without it, the numbers won’t line up nicely.