Practice: Multiplication Table

Practice: Multiplication Table

This exercise combines range, list building, and f-strings.

Exercise

  1. Define a function named multiplication_table with two parameters: n and upto.
  2. It returns a list of strings — the multiplication table for n from 1 to upto (inclusive). Each entry has the form <n> x <i> = <product>.

multiplication_table(3, 4) returns:

['3 x 1 = 3', '3 x 2 = 6', '3 x 3 = 9', '3 x 4 = 12']

Run your code to see the output, then press Submit.

Hints

  • range(1, upto + 1) produces 1 through upto.
  • Build each entry with an f-string and append it to a result list.

Tests

import unittest


class TestMultiplicationTable(unittest.TestCase):
    def test_table_of_3_up_to_4(self):
        self.assertEqual(
            multiplication_table(3, 4),
            ["3 x 1 = 3", "3 x 2 = 6", "3 x 3 = 9", "3 x 4 = 12"],
        )

    def test_table_of_7_up_to_1(self):
        self.assertEqual(multiplication_table(7, 1), ["7 x 1 = 7"])

    def test_upto_0_gives_an_empty_table(self):
        self.assertEqual(multiplication_table(5, 0), [])
def multiplication_table(n, upto):
    table = []
    for i in range(1, upto + 1):
        table.append(f"{n} x {i} = {n * i}")
    return table


for line in multiplication_table(3, 4):
    print(line)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.