Python中函数未定义错误

2024-03-29 09:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python中定义一个基本函数,但是当我运行一个简单的测试程序时,总是会出现以下错误

>>> pyth_test(1, 2)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    pyth_test(1, 2)
NameError: name 'pyth_test' is not defined

这是我用于此函数的代码

def pyth_test (x1, x2):
    print x1 + x2

更新:我打开了名为pyth.py的脚本,然后在解释器中输入pyth_test(1,2),当它给出错误时。

谢谢你的帮助。(对于这个基本问题,我表示歉意,我以前从未编写过程序,现在正努力把学习Python作为一种爱好)


import sys
sys.path.append ('/Users/clanc/Documents/Development/')
import test


printline()



## (the function printline in the test.py file
##def printline():
##   print "I am working"

Tags: the函数inpytestimport定义def
3条回答

它对我有效:

>>> def pyth_test (x1, x2):
...     print x1 + x2
...
>>> pyth_test(1,2)
3

确保在调用函数之前定义了函数。

在python中,函数不能从任何地方神奇地访问(就像在php中一样)。必须先申报。所以这是可行的:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1, 2)

但这不会:

pyth_test(1, 2)

def pyth_test (x1, x2):
    print x1 + x2

是的,但是在哪个文件中声明了pyth_test的定义?它在被调用之前是否也位于?

编辑:

要将其置于透视图中,请创建一个名为test.py的文件,其中包含以下内容:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

现在运行以下命令:

python test.py

你应该看到你想要的结果。现在,如果您正在交互会话中,则应如下所示:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

我希望这能解释宣言是如何运作的。


为了让您了解布局的工作原理,我们将创建一些文件。创建一个新的空文件夹,用以下命令保持干净:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

程序.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

现在如果你跑:

python program.py

它将打印出3。现在为了解释出了什么问题,让我们这样修改我们的程序:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

现在让我们看看会发生什么:

$ python program.py 
Traceback (most recent call last):
  File "program.py", line 3, in <module>
    pyth_test(1,2)
NameError: name 'pyth_test' is not defined

如上所述,由于上述原因,python找不到模块。因此,您应该将声明放在首位。

现在,如果我们运行交互式python会话:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

同样的过程也适用。现在,包导入并不是那么简单,所以我建议您研究一下modules work with Python。我希望这对你有所帮助,祝你好运!

相关问题 更多 >