Tom
Tom

Reputation: 71

Multiplying Calculator Function in Python

I wrote the code below with "return", but it doesn't work. What do I need to change in my code (return line) to get the correct result?

def multiply():
    integer_1 = int(input("enter a whole number: "))
    integer_2 = int(input("enter a whole number: "))
    answer = integer_1 * integer_2
    return(str(integer_1), "*", str(integer_2), "=", answer)

multiply()

My output:

('9', '*', '13', '=', 117)

Desired output:

9 * 13 = 117

Upvotes: 0

Views: 1191

Answers (3)

Joshua Varghese
Joshua Varghese

Reputation: 5202

Return isn't a function. Also the use of joining the items of the list helps.

def multiply():
    integer_1 = int(input("enter a whole number: "))
    integer_2 = int(input("enter a whole number: "))
    answer = integer_1 * integer_2
    return ' '.join((str(integer_1), "*", str(integer_2), "=", str(answer)))

print(multiply()) #print() is used to print the data without '

or just:

return str(integer_1) + " * " + str(integer_2) + " = " + str(answer)

Upvotes: 1

Lab
Lab

Reputation: 226

Return is not a function, so the correct syntax should be:

return str(integer_1)+" * "+str(integer_2)+" = "+str(answer)

Where + means to combine two strings together.

Upvotes: 1

Kurt Kline
Kurt Kline

Reputation: 2069

You can use f-strings for this:

return(f'{integer_1} * {integer_2} = {answer}')

This allows you to create your output statement without any string concatenation.

And since you are returning a value, you must assign the output of multiply() to a variable. For example:

output = multiply()

So in full:

def multiply():
    integer_1 = int(input("enter a whole number: "))
    integer_2 = int(input("enter a whole number: "))
    answer = integer_1 * integer_2
    return(f'{integer_1} * {integer_2} = {answer}')

output = multiply()
print(output)

See this article about f-strings from realpython.com

Upvotes: 1

Related Questions