Ex 13: Multiplication Table
Problem
Generate a multiplication table for an educational app. We need to create a list of formatted strings representing the table for a given number.
Rules
- Define
multiplication_table(number: int) -> list[str]. - Use
range(1, 11)to generate rows for multipliers 1 through 10. - Return a list of strings in the format:
"number x multiplier = result".
Boilerplate
Copy below code and paste to our IDE for head start.
# Write our code inside this function
def multiplication_table(number: int) -> list[str]:
pass # remove this
# Call with test data
print(multiplication_table(6))
Expected Output
['6 x 1 = 6', '6 x 2 = 12', '6 x 3 = 18', '6 x 4 = 24', '6 x 5 = 30', '6 x 6 = 36', '6 x 7 = 42', '6 x 8 = 48', '6 x 9 = 54', '6 x 10 = 60']
Solution
Only view the solution after trying our best.
Show solution
def multiplication_table(number: int) -> list[str]:
table: list[str] = []
for i in range(1, 11):
table.append(f"{number} x {i} = {number * i}")
return table
# Test call
print(multiplication_table(6))
Details
Using range(1, 11) is the standard way to get a sequence from 1 to 10 inclusive. Since the stop parameter is exclusive, we use 11 to ensure 10 is included in the output.