Erik.E
Erik.E

Reputation: 39

All I get is "NameError: name 'x' is not defined" error

I am new to python and I am trying to make a function that calculates the derivative of another function. So far I have this code

def f(x):
   return x**2 + x - 5

def derivative(f,x,h):
    return 1/(2*h) * (f(x+h) - f(x-h))

print derivative(f(x),4,6)

but when I try to run it I get "NameError: name 'x' is not defined" error, can someone help me?

Upvotes: 0

Views: 73173

Answers (3)

Santosh
Santosh

Reputation: 1

class Assign:

def _init_(self,x,y):
    self.x=x
    self.y=y

def sub(self,x,y):
    return x-y 

num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))

obj=Assign()

if x<=0:
    print(num1,"-",num2,"=","he's the messiah he's a very naughty boy", obj.sub(num1,num2))

elif x>=0:
    print(num1,"-",num2,"=","Yes we all are individuals", obj.sub(num1,num2))

else:
    print("invalid input")

Upvotes: 0

ergonaut
ergonaut

Reputation: 7057

x is not defined, and you cannot pass f(x) in the parameter. Try doing something like this:

def f(x):
return x**2 + x - 5

def derivative(f,x,h):
return 1/(2*h) * (f(x+h) - f(x-h))

x=12345

print derivative(f,x,6)

Upvotes: 3

IfTrue
IfTrue

Reputation: 543

When you tell it to :

print derivative(f(x),4,6) 

you haven't defined the x you are passing as a parameter in f(x).

You can do that like so, for example with x = 1 :

def f(x):
   return x**2 + x - 5

def derivative(f,x,h):
    return 1/(2*h) * (f(x+h) - f(x-h))

x=1

print derivative(f(x),4,6)

Upvotes: 2

Related Questions