函数未定义 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"

原文由 Lance Collins 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 513
2 个回答

是的,但是在哪个文件中声明了 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
>>>

我希望这可以解释声明的工作原理。


为了让您了解布局的工作原理,我们将创建一些文件。使用以下内容创建一个新的空文件夹以保持内容清洁:

我的函数.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

同样的过程适用。现在,包导入并不是那么简单,所以我建议您研究 模块如何与 Python 一起工作。我希望这对您有所帮助,并祝您学习顺利!

原文由 onteria_ 发布,翻译遵循 CC BY-SA 3.0 许可协议

这个对我有用:

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

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

原文由 AJ. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题