Lab: Nested Loops#

Note

Source: Adapted from the C# edition (for/lab-nested-loops.rst). Exercises translated to Python idioms. print_reps and string_of_reps replace C# methods of the same name; factorial and print_rectangle follow the same logic. The multiplication table is a Python addition.

Goals for this lab:

  • Practice for loops with range().

  • Use nested loops to produce two-dimensional output.

  • Build strings by accumulation.

2. string_of_reps#

Write a function string_of_reps(s, count) that returns a string consisting of s repeated count times (without printing).

>>> string_of_reps("ab", 3)
'ababab'

Build the result by accumulating into an initially empty string using a for loop. After you have it working, verify that s * count gives the same answer — this is Python’s built-in way to repeat a string.

3. factorial#

Write a function factorial(n) that returns n! = 1 × 2 × … × n iteratively. Use range(1, n + 1) and a running product:

n = 0 → 1
n = 1 → 1
n = 5 → 120
n = 6 → 720

Think through the starting value of your accumulator before coding.

After it passes basic tests, find the largest value of n for which Python gives a correct answer. (Hint: Python integers have arbitrary precision, so you may be surprised.)

5. Multiplication Table#

Write a function mult_table(n) that prints an n × n multiplication table with row and column headers. Example call:

mult_table(5)

Expected output:

 * |  1  2  3  4  5
-------------------
 1 |  1  2  3  4  5
 2 |  2  4  6  8 10
 3 |  3  6  9 12 15
 4 |  4  8 12 16 20
 5 |  5 10 15 20 25

Suggestions:

  • Compute the column width from len(str(n * n)) so the table scales.

  • Print the header row with a for loop, then a separator line, then the body rows using nested loops.

  • Use an f-string with a computed field width for alignment.

This exercise is similar to the modular multiplication table in For Loop Examples but without the modulus operation.