创建乘法函数 - Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37820896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:58:15  来源:igfitidea点击:

Creating a Multiplying Function - Python

pythonfunctionmultiplying

提问by Ivan

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

回答by Matt Cremeens

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.

只知道第二个脚本将累积地乘以列表中的数字。

回答by Cat

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.

Multiply 函数将把两个数字作为参数,将它们相乘,然后返回结果。当提供 2 和 3 时,我让它打印函数的返回值。它应该打印 6,因为它返回这两个数字的乘积。

回答by JohnT

Isn't this a little easier and simpler?

这不是更容易更简单一些吗?

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

print(multiply(2,3))

回答by Aziz Zoaib

This should work.

这应该有效。

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

and then call function like

然后调用函数

print(numbermultiplier(2,4))

print(numbermultiplier(2,4))

回答by Andre Machado

It's easier than you thought

这比你想象的要容易

from operator import mul

mul(2,2)