Creating a multiplying function

Question:

I don’t understand how to make a function and then make it work which will allow me to multiply.
For E.g.

def Multiply(answer):
    num1,num2 = int(2),int(3) 
    answer = num1 * num2
    return answer

print(Multiply(answer))

I Had a go at making one and didnt work so the one below is where i found on internet but i have no idea how to make it work as in print out the numbers timed.

def multiply( alist ):
     theproduct = 1
     for num in alist: theproduct *= num
     return theproduct
Asked By: Ivan

||

Answers:

I believe you have your parameter as your return value and you want your paramters to be inputs to your function. So try

def Multiply(num1, num2):
    answer = num1 * num2
    return answer

print(Multiply(2, 3))

As for the second script, it looks fine to me. You can just print the answer to the console, like so (notice it takes a list as an argument)

print multiply([2, 3])

Just know that the second script will multiply numbers in the list cumulatively.

Answered By: Matt Cremeens

I believe this is what you’re looking for:

def Multiply( num1, num2 ): 
    answer = num1 * num2
    return answer

print(Multiply(2, 3))

The function Multiply will take two numbers as arguments, multiply them together, and return the results. I’m having it print the return value of the function when supplied with 2 and 3. It should print 6, since it returns the product of those two numbers.

Answered By: Cat

Isn’t this a little easier and simpler?

def multiply(a,b):
    return a*b

print(multiply(2,3))
Answered By: JohnT

This should work.

def numbermultiplier(num1, num2): 
      ans = num1 * num2 
      return ans

and then call function like

print(numbermultiplier(2,4))

Answered By: Aziz Zoaib

It’s easier than you thought

from operator import mul

mul(2,2)
Answered By: Andre Machado

Is that actually what you needed?

 def multiple(number, multiplier, *other):
    if other:
        return multiple(number * multiplier, *other)
    return number * multiplier
Answered By: HaskSy

If for some reason you want to multiply without using "*"

def multiply(x, y):
    x = int(inp1)
    y2 = int(inp2)
    y = 1
    x2 = x
    while y < y2:
        x2 += x
        y += 1
    print(x2)
Answered By: digitalGangster

If you don’t want to use * (which I’m guessing you don’t), you can do this:

def multiply(x, y):
    a = 0
    x2 = int(x)
    y2 = int(y)
    for i in range(y2):
        a += x2
    return a
print(multiply(2,4))

but I recommend using * since its easier than this ^

Answered By: dark vader

For multiplying n numbers you can use eval

def multiply(*nums):
   return eval('*'.join(nums))
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.