Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 321
Cupitor Avatar asked Sep 03 '26 14:09

Cupitor


1 Answers

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…

like image 132
abarnert Avatar answered Sep 05 '26 05:09

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!