Python 我得到的只是“NameError: name 'x' is not defined”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32723961/
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 12:08:13  来源:igfitidea点击:

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

pythonnameerror

提问by Erik.E

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

我是 python 的新手,我正在尝试创建一个计算另一个函数的导数的函数。到目前为止我有这个代码

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?

但是当我尝试运行它时,我收到“NameError: name 'x' is not defined”错误,有人可以帮助我吗?

回答by IfTrue

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).

你还没有定义你在 f(x) 中作为参数传递的 x。

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

你可以这样做,例如 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)

回答by ergonaut

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

x 未定义,您不能在参数中传递 f(x)。尝试做这样的事情:

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)

回答by Santosh

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")