函数未定义Python中的错误

Lan*_*ins 28 python function

我试图在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
Run Code Online (Sandbox Code Playgroud)

这是我用于此功能的代码;

def pyth_test (x1, x2):
    print x1 + x2
Run Code Online (Sandbox Code Playgroud)

更新:我有一个名为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"
Run Code Online (Sandbox Code Playgroud)

ont*_*ia_ 37

是的,但在什么文件pyth_test的定义声明?它还被称为它之前的位置吗?

编辑:

要进行透视,请创建一个test.py使用以下内容调用的文件:

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

pyth_test(1,2)
Run Code Online (Sandbox Code Playgroud)

现在运行以下命令:

python test.py
Run Code Online (Sandbox Code Playgroud)

你应该看到你想要的输出.现在,如果您正在进行交互式会话,它应该是这样的:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 
Run Code Online (Sandbox Code Playgroud)

我希望这能解释声明是如何运作的.


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

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 
Run Code Online (Sandbox Code Playgroud)

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)
Run Code Online (Sandbox Code Playgroud)

现在,如果您运行:

python program.py
Run Code Online (Sandbox Code Playgroud)

它将打印出来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
Run Code Online (Sandbox Code Playgroud)

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

$ 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
Run Code Online (Sandbox Code Playgroud)

如上所述,由于上述原因,python无法找到该模块.因此,您应该将声明保持在最顶层.

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

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3
Run Code Online (Sandbox Code Playgroud)

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


blu*_*ume 8

在 python 中,函数不能从任何地方神奇地访问(就像它们在 php 中一样)。必须首先声明它们。所以这会起作用:

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

pyth_test(1, 2)
Run Code Online (Sandbox Code Playgroud)

但这不会:

pyth_test(1, 2)

def pyth_test (x1, x2):
    print x1 + x2
Run Code Online (Sandbox Code Playgroud)


AJ.*_*AJ. 7

这个对我有用:

>>> def pyth_test (x1, x2):
...     print x1 + x2
...
>>> pyth_test(1,2)
3
Run Code Online (Sandbox Code Playgroud)

确保调用之前定义函数。