Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Loops Within Loops

Loops within loops, also known as nested loops, occur frequently in programming, so it is helpful to see a few examples. For instance, here’s a program that prints out the times tables up to 10:

for row in range(1, 10):
    for col in range(1, 10):
        prod = row * col
        if prod < 10:
            print(' ', end = '')
        print(row * col, ' ', end = '')

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.

  • + Share This
  • 🔖 Save To Your Account