Error in Python: missing 1 required positional argument - python

I'm not so good with python and I keep getting this error:
TypeError: demand_curve() missing 1 required positional argument: 'pb'
And this is my code:
P,c,Q,y,pb,N,X,pf,t=sp.symbols('P c Q y pb N X pf t')
def demand_curve(c,Q,y,pb):
demand = (c.log(Q)-(-4.507+(0.841*y)+(0.2775*pb)))/(-0.397)
return demand
Q_num = np.linspace(0,100,100)
fig,ax=plt.subplots()
ax.set_ylabel('P')
ax.set_xlabel('E')
ax.plot(demand_curve(Q_num, 50, 2), Q_num,label='E (a=100,b=2)')
#legend:
ax.legend(loc='upper right', frameon=False)
ax.set(xlim=(0,100))
ax.set(ylim=(0,60))
I don't really understand what is the problem, can someone help me?

When you declare your function you do this :
def demand_curve(c,Q,y,pb):
...
So you have four parameters c, Q, y and pb, later in the code you call it using :
demand_curve(Q_num, 50, 2)
So in the way you call it you have
c = Q_num
Q = 50
y = 2
pb = Nothing at all
And python don't like this so you should provide and additional value when you call this function or provide a default value for the last parameter for example :
def demand_curve(c,Q,y,pb = "a default value"):
...

You are not passing all the arguments value when you call you function "demand_curve". Your function "demand_curve(c,Q,y,pb)" required 4 positional arguments but you give only 3 at "demand_curve(Q_num, 50, 2)".

Related

Fibonacci Measurement Algorithm implementation: missing 1 required positional argument: 'p'

I've implemented a fibonacci Measurement algorithm with 2 parameter n and p.
I got this issue,
TypeError Traceback (most recent call last)
<ipython-input-19-295638b26e62> in <module>
2 N = 10
3 # [F(n,p) for n in range(N)]
----> 4 print(F(10,1))
<ipython-input-12-fda62c8ec9a6> in F(n, p)
6 elif n <= p+1:
7 return n
----> 8 return F(n-1) + F(n-p-1)
TypeError: F() missing 1 required positional argument: 'p'
I have input 2 parameters n =10, p = 1, but still having this problem "missing 1 required argument". Does anyone know why and solution for this or any suggestion would be appreciated!
There could be two potential issues.
You're calling a function, F, that doesn't seem to be defined in the snippet you've attached. You might want to change it to fibonacci_of if it is supposed to call itself recursively. In addition, since the fibonacci_of accepts two parameters, you would need to call it with two arguments
If F is already defined elsewhere, it is supposed to accept more than one argument. You could check its function definition and see the parameter requirements. See attached examples.
def square(a): # Requires single parameter.
return a ** 2
def add(a, b): # Requires two parameters.
return a + b

Incomprehensible syntax in Python - passing variables as arguments

I cannot find anywhere why to use and if are there any diffrences between these 2 calls:
someFunction(10)
and
someFunction(x=10)
Your initial invocation of the function is using a positional argument - that is, it will match the '10' with the first parameter of the argument.
However, if you explicitly call the function with a keyword argument, it will match the value with the specified keyword.
def kwarg_func(x = 5, y = 10, z = 2):
return x * y * z
# will return 200 (10 * 10 * 2)
print(kwarg_func(10))
# will return 10 (5 * 1 * 2)
print(kwarg_func(y = 1))
# will throw an error since keyword 'a' is undefined
print(kwarg_func(a = 1))
So the reason you'd really be passing x=10, is if it was a **kwarg or if x is set in the variable
def somefunction(x=5):
print(x*x)
somefunction(x=10)
That would result in 10*10, thus 100.
The reason behind this is that Python accepts positional arguments which are effectively:
def somefunction(x)
#dosomestuff
Where x in somefunction is in position 0 for the arguments you can pass to it.
Where as:
def somefunction(x=10)
#dosomestuff
Is a keyword argument (but you can use its position as well)
A positional argument must be before a keyword argument.
The python tutorial has a good touch on this: https://docs.python.org/3/tutorial/controlflow.html#defining-functions
Your question is a bit vague and it depends on your function construction.
Suppose, you have a function:
def someFunction(x):
return x
Then you can call it via someFunction(10) or someFunction(x=10) while the latter is more verbose but the first will totally suffice. Look up args and **kwargs for a better understanding, e.g. here.
there is a major importance of args and kwargs. first of all 10 is the arg(argument) and x=10(keyword argument) is called kwarg.
the most basic difference between these two is args are taken in order and kwargs are not.
kwargs can be given in any order.
before reading this answer I hope you have some knowledge on python default arguments.
def func(a=25, b, c, d=3, e, f=2, g, h=1, i):
return a * b * c * d * e * f * g * h * i
in this function, you can pass all the arguments or you can pass only essential arguments
essential arguments are b, c, e, g, i
and default arguments are a, d, f, h.
So the question becomes how to pass values only for essential arguments.
the answer is kwargs. since for kwargs, there is no importance of the order we can pass the arguments as func(b=3, c=4, e=2, g=10) or func(c=4, g=10, b=3, e=2) any combination would work for this.

Python: maximization of function

Suppose I have the following simple function and inputs:
dates = pd.date_range('20170101',periods=20)
a1 = np.ones(3)
b1 = pd.DataFrame(np.random.randint(10,size=(20,3)),index=dates,columns=['foo','bar','see'])
def test_func(a,b):
c = (a*b).sum(axis=1)
d = c.std()*np.sqrt(3)
e = c.mean()/d
return -np.array(e)
I would like to solve this function for a that minimizes the output (maximizes e).
scipy.optimize.fmin(test_func,a1,args=(b1))
But this throws a type error
TypeError: test_func() takes 2 positional arguments but 4 were given
My quesiton is i) is this a good way to solve for the max of such a function and ii) what the devil is the problem?
You are missing a comma after the b1 in the extra argument:
scipy.optimize.fmin(test_func,a1,args=(b1,))
seems to work.

TypeError: p_vinet() takes 2 positional arguments but 4 were given

I am trying to pass arguments to a function and I think I'm doing it correctly but it still gives the error:
TypeError: p_vinet() takes 2 positional arguments but 4 were given
Here's the pieces of my code first and then I'll give the part that gives the error.
volumeMgO is a previously calculated array consisting of:
array([ 7.64798549, 7.67153344, 7.67153344, 7.8068763 , 7.97288941,
8.14781986, 8.33321177, 8.53118834, 8.74433596, 8.97545339,
9.22826581, 9.50740563, 9.81962839])
params_MgO is this:
params_MgO = [11.244, 160., 4.0]
The vinet function is:
def p_vinet(v, params):
"""
This function will calculate pressure from Vinet equation.
Parameters
==========
v = volume
params = [V0, K0, K0']
Returns
=======
Pressure calculated from Vinet equation
"""
f_v = np.power( v/params[0], 1./3.)
eta = 1.5 * (params[2] - 1.)
P = 3 * params[1] * ((1 - f_v) / np.power(f_v, 2) ) * np.exp(eta * (1 -
f_v))
return P
Finally, the slope function is just a simple way of taking a derivative:
def slope(func, x, h, args=()):
"""
find a slope for function f at point x
Parameters
=========
f = function
x = independent variable for f
h = distance along x to the neighboring points
Returns
=======
slope
"""
rise = func(x+h, *args) - func(x-h, *args)
run = 2.*h
s = rise/run
return s
Now here is where the issue comes. When I type:
BulkModulus_MgO = np.zeros(volumeMgO.size)
for i in range(volumeMgO.size):
BulkModulus_MgO[i] = slope(p_vinet, volumeMgO[i], volumeMgO[i]*0.0001,
args=(params_MgO))
I get this error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-116-60467d989bbc> in <module>()
1 BulkModulus_MgO = np.zeros(volumeMgO.size)
2 for i in range(volumeMgO.size):
----> 3 BulkModulus_MgO[i] = slope(p_vinet, volumeMgO[i],
volumeMgO[i]*0.0001, args=(params_MgO))
<ipython-input-100-618f25e85d34> in slope(func, x, h, args)
15 """
16
---> 17 rise = func(x+h, *args) - func(x-h, *args)
18 run = 2.*h
19
TypeError: p_vinet() takes 2 positional arguments but 4 were given
I don't get it. p_vinet needs arguments v and params, and I supply v through the x+h and x-h in the slope function, and the params is a list with 3 entries that p_vinet unpacks. So that's 2 arguments. Why is it saying I'm supplying 4?
Sorry if it's slightly confusing how I'm presenting the code. I'm coding in jupyter notebook and all the functions are separate. volumeMgO is calculated separately from previous code with no issues.
Let's look at this line of code:
BulkModulus_MgO[i] = slope(p_vinet, volumeMgO[i], volumeMgO[i]*0.0001,
args=(params_MgO))
args should be like this: args=(params_MgO,) (tuple with one element in it) instead of args=(params_MgO) (not tuple, just array of 3 elements) because in second case unpacking *args in slope() function gives you 3 additional arguments (each element of params_MgO). That's why you got 4 arguments in slope() function. In first case unpacking gives you entire array as single parameter (like params in p_vinet() function).

Function missing 2 required positional arguments: 'x' and 'y'

I am trying to write a Python turtle program that draws a Spirograph and I keep getting this error:
Traceback (most recent call last):
File "C:\Users\matt\Downloads\spirograph.py", line 36, in <module>
main()
File "C:\Users\matt\Downloads\spirograph.py", line 16, in main
spirograph(R,r,p,x,y)
File "C:\Users\matt\Downloads\spirograph.py", line 27, in spirograph
spirograph(p-1, x,y)
TypeError: spirograph() missing 2 required positional arguments: 'x' and 'y'
>>>
This is the code:
from turtle import *
from math import *
def main():
p= int(input("enter p"))
R=100
r=4
t=2*pi
x= (R-r)*cos(t)-(r+p)*cos((R-r)/r*t)
y= (R-r)*sin(t)-(r+p)*sin((R-r)/r*t)
spirograph(R,r,p,x,y)
def spirograph(R,r,p,x,y):
R=100
r=4
t=2*pi
x= (R-r)*cos(t)-(r+p)*cos((R-r)/r*t)
y= (R-r)*sin(t)-(r+p)*sin((R-r)/r*t)
while p<100 and p>10:
goto(x,y)
spirograph(p-1, x,y)
if p<10 or p>100:
print("invalid p value, enter value between 10 nd 100")
input("hit enter to quite")
bye()
main()
I know this maybe has a simple solution but I really can't figure out what I am doing wrong, this was an exercise in my computer science 1 class and I have no idea how to fix the error.
The last line of the traceback tells you where the problem is:
File "C:\Users\matt\Downloads\spirograph.py", line 27, in spirograph
spirograph(p-1, x,y) # <--- this is the problem line
TypeError: spirograph() missing 2 required positional arguments: 'x' and 'y'
In your code, the spirograph() function takes 5 arguments: def spirograph(R,r,p,x,y), which are R, r, p, x, y. In the line highlighted in the error message, you are only passing in three arguments p-1, x, y, and since this doesn't match what the function is expecting, Python raises an error.
I also noticed that you are overwriting some of the arguments in the body of the function:
def spirograph(R,r,p,x,y):
R=100 # this will cancel out whatever the user passes in as `R`
r=4 # same here for the value of `r`
t=2*pi
Here is a simple example of what is happening:
>>> def example(a, b, c=100):
... a = 1 # notice here I am assigning 'a'
... b = 2 # and here the value of 'b' is being overwritten
... # The value of c is set to 100 by default
... print(a,b,c)
...
>>> example(4,5) # Here I am passing in 4 for a, and 5 for b
(1, 2, 100) # but notice its not taking any effect
>>> example(9,10,11) # Here I am passing in a value for c
(1, 2, 11)
Since you always want to keep this values as the default, you can either remove these arguments from your function's signature:
def spirograph(p,x,y):
# ... the rest of your code
Or, you can give them some defaults:
def spirograph(p,x,y,R=100,r=4):
# ... the rest of your code
As this is an assigment, the rest is up to you.
The error tells you that you're using too few arguments to call spirograph
Change this code:
while p<100 and p>10:
goto(x,y)
spirograph(R,r, p-1, x,y) # pass on the missing R and r
You're not using these arguments though, but you still have to give them to the function to call it.

Categories