What does an equality mean in function arguments in python? [duplicate]

Deadly 提交于 2021-02-04 19:35:44

问题


This is an example of of code from here:

What does the equality mean in the argument assignment to function? like N=20000 here? What is the difference between that and simply N as argument? import random,math

def gibbs(N=20000,thin=500):
   x=0
   y=0
   samples = []
   for i in range(N):
       for j in range(thin):
           x=random.gammavariate(3,1.0/(y*y+4))
           y=random.gauss(1.0/(x+1),1.0/math.sqrt(x+1))
       samples.append((x,y))
   return samples

smp = gibbs()

回答1:


In a function definition, it specifies a default value for the parameter. For example:

>>> def func(N=20000):
...     print(N)
>>> func(10)
10
>>> func(N=10)
10
>>> func()
20000

In the first call, we're specifying a value for the N parameter with a positional argument, 10. In the second call, we're specifying a value for the N parameter with a keyword argument, N=10. In the third call, we aren't specifying a value at all—so it gets the default value, 20000.

Notice that the syntax for calling a function with a keyword argument looks very similar to the syntax for defining a function with a parameter with a default value. This parallel isn't accidental, but it's important not to get confused by it. And it's even easier to confuse yourself when you get to unpacking arguments vs. variable-argument parameters, etc. In all but the simplest cases, even once you get it, and it all makes sense intuitively, it's still hard to actually get the details straight in your head. This blog post attempts to get all of the explanation down in one place. I don't think it does a great job, but it does at least have useful links to everything relevant in the documentation…




回答2:


It specifies a default value. This can be especially useful if the program will fail on an undefined value. For instance, if it was simply n, and you did not feed the function any variables it would fail. With the default it does not.



来源:https://stackoverflow.com/questions/19526871/what-does-an-equality-mean-in-function-arguments-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!