-2
numbers = (2,3,4)
def product(n):
    m = 1
    for i in n:
        m *= i
        return print(numbers[0],'x',numbers[1],'x',numbers[2],'=',m)
product(numbers)

This is what I wrote for this problem. But I don't know how to make the result like "2x3x4=24" exactly. Another question is if I add '5' in the parentheses, it only shows "2x3x4=120", I cannot get "2x3x4x5=120". Could anyone helps me to fix my code??? Thanks.

  • 1
    Does this answer your question? [What's the function like sum() but for multiplication? product()?](https://stackoverflow.com/questions/595374/whats-the-function-like-sum-but-for-multiplication-product) – 0x263A Oct 04 '22 at 00:07
  • your return statement is inside the loop, so the function returns at the end of the first iteration. You want to return *after* the loop finishes. – President James K. Polk Oct 04 '22 at 00:27
  • Hi,0x263A. Thank you that you share the link, but this does not answer my question. – ooooouo523 Oct 04 '22 at 04:34
  • you can use `from functools import reduce` and then `print(" X ".join(map(str, a)), " = ", reduce(lambda x1,x2: x1 * x2, a))` – Deepak Tripathi Oct 04 '22 at 07:19

1 Answers1

0

There are two main issues with your code. The first in that your return statement is executed in the first iteration of your loop, but you want it to happen after the entire loop has finished. This happens because you have too much whitespace to the left of the return statement. The second is that you’re attempting to return the return value of a call to print. To fix this ditch the return or even better return a string then print that:

numbers = (2,3,4)
def product(n):
    m = 1
    for i in n:
        m *= i
    return f"{n[0]}x{n[1]}x{n[2]}={m}"

returned = product(numbers)
print(returned)

The answer linked in the comments points out there’s an even easier way to do this:

from math import prod
returned = prod((2,3,4))
print(returned)

And here's a bit of a kick-flip for fun:

from math import prod
numbers = (2,3,4)
print(*numbers, sep="x", end=f"={prod(numbers)}")
0x263A
  • 1,807
  • 9
  • 22