Example 2: Printing pairs of integers

Given are two integers n and m. Integer n represents the number of rows and integer m represents the number of columns. We want to print an n by m table where each entry is a pair of integers such that

  • the first integer is  between 1 and n
  • the second integer is between 1 and m
  • each pair r c  is in row r and column c in the table (as shown below)
Please input the integer the number of rows: 5
Please input the integer the number of columns: 7 

11 12 13 14 15 16 17
21 22 23 24 25 26 27
31 32 33 34 35 36 37
41 42 43 44 45 46 47
51 52 53 54 55 56 57

We use one loop (the inner loop) to print one row of m pairs and we use a second loop (the outer loop) to advance to the next row.  This is achieved by using two nested for-loops.

# 03Loops example_02_printing pairs.py

n = int(raw_input('Please input the integer the number of rows: '))

m = int(raw_input('Please input the integer the number of columns: '))

for row in range(1,n+1):

   for column in range(1,m+1):

     print str(row)+str(column),

   print      # finish current row and advance to next row

How would we generate the table without nested loops? For any fixed n, say n=5, we would have to write five for-loops, each printing one row.  If we were to change n, we would need to add or delete code corresponding to loops. This would be rather inconvenient. Nested loop constructions are crucial in many computations!