Write a function that builds the first ten multiples of n, as a single space-separated string.
multiplication_table(n)
Return "n*1 n*2 n*3 ... n*10" — the actual products, space-separated, not the literal expressions.
multiplication_table(3) // → "3 6 9 12 15 18 21 24 27 30"
multiplication_table(1) // → "1 2 3 4 5 6 7 8 9 10"
This combines the accumulator pattern with building a string instead of a number — a very common variant.
def multiplication_table(n):
values = []
for i in range(1, 11):
values.append(str(n * i))
return " ".join(values)
range(1, 11) produces 1 through 10 — ten numbers, matching "the first ten multiples". For each i, n * i computes the multiple, and str(...) converts it to text so it can be joined into a string later (you can't " ".join(...) a list of numbers directly — join only works on strings).
" ".join(values) is the idiomatic way to combine a list of strings with a separator between each — much cleaner than manually concatenating with + and tracking whether you're on the first element (which would otherwise need special-casing to avoid a leading space).
A subtle but important detail: building up a list and joining it once at the end is generally preferred over repeatedly concatenating strings with += inside a loop — string concatenation in a loop creates a new string object on every iteration, which gets wasteful as the loop grows.
def multiplication_table(n):
values = []
for i in range(1, 11):
values.append(str(n * i))
return " ".join(values)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.