Me All
Me All

Reputation: 269

Adding several numbers and returning output as equation

I am defining a function that would take several numbers as input and would return the total sum of all of them. How many numbers will be part of the input is unknown. Also, the output of this function must contain the mathematical equation that was followed to get that result.

For example, if these numbers are given when calling the function: 2, 3, 2, 1; the function would calculate the total sum, that is 8, and would output the following: 2 + 3 + 2 + 1 = 8 (as a string).

So far, I was able to do the first part (i.e., the calculation), but I don't know how to create the return statement that would output the mathematical equation. Here's what I have:

def my_math(*args):
    sum = 0
    for n in args:
        sum += n
    return "= {}".format(sum) #this is where I'm stuck. I don't know how to code the numbers and the '+' signs that would appear before the '=' sign

Upvotes: 1

Views: 68

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40048

You can use string.format with string.join

return "{} = {}".format(' + '.join(map(str,args)),sum(args))

Upvotes: 0

Jonno_FTW
Jonno_FTW

Reputation: 8809

Use the join method:

return " + ".join(str(x) for x in args) + f" = {sum}"

I use an f-string here to simplify the formatting.

Upvotes: 1

Related Questions