Python 名称错误:全局名称“;总数;没有定义,但它是
每次我运行代码时,它都告诉我没有定义总计。我在support.py中定义了它,然后将其导入stopping.py。我找过类似的案例,但我不明白为什么它会告诉我这些。请帮忙 这是停下来了Python 名称错误:全局名称“;总数;没有定义,但它是,python,variables,global,Python,Variables,Global,每次我运行代码时,它都告诉我没有定义总计。我在support.py中定义了它,然后将其导入stopping.py。我找过类似的案例,但我不明白为什么它会告诉我这些。请帮忙 这是停下来了 from support import * def main(): def get_info(): amplitude = float(input("Amplitude of the sine wave (in feet): ")) period = float(input("
from support import *
def main():
def get_info():
amplitude = float(input("Amplitude of the sine wave (in feet): "))
period = float(input("Period of the sine wave (in feet): "))
sign = float(input("Distance to the stop sign (in feet): "))
nobrake = float(input("Distance needed to stop without using hand brakes (in feet): "))
step = 9
return amplitude, period, sign, nobrake
get_info()
get_distance(0, 0, 155.3, 134.71)
print("Distance to the stop sign (in feet): 155.3")
print("Distance needed to stop without using hand brakes (in feet): 350.5")
print("Length of the sine wave: ", total)
main()
这是support.py
import math
def get_sine_length(amplitude, period, x_distance, step):
x = 0.0
total = 0.0
last_x = 0
last_y = 0
while x <= x_distance + (step / 2):
y = math.sin(2 * math.pi / period * x) * amplitude
dist = get_distance(last_x, last_y, x, y)
#print("distance from (", last_x, ",", last_y, ") to (", x, ",", y, ") is", dist)
total = total + dist
last_x = x
last_y = y
x = x + step
return total
def get_distance(a, b, c, d):
dx = c - a
dy = d - b
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
导入数学
def get_正弦长度(振幅、周期、x_距离、步长):
x=0.0
总计=0.0
last_x=0
最后的y=0
而xtotal
是本地的get\u sine\u length
。由于您要返回它,因此要访问它,请调用get\u sine\u length
并存储结果
这个问题实际上与导入
没有任何关系。如果get\u sine\u length
的函数定义位于stopping.py
中,则情况相同。函数中定义的变量(在def someFunc():
中)只能由该函数访问,除非您强制它们为全局变量。然而,大多数时候,您不应该仅仅为了从函数外部访问通常的局部变量而声明全局变量——这就是返回的目的
此示例显示了您遇到的一般问题。我不敢说这是个问题,因为它实际上是python(和许多其他编程语言)的一个重要语言特性
>>def func():
... localVar=“func()一运行完,我就消失了。”
...
>>>打印本地变量
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
NameError:未定义名称“localVar”
>>>func()
>>>打印本地变量
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
NameError:未定义名称“localVar”
把函数想象成一台机器,它接收某些输入并输出其他输入。您通常不想打开机器-您只想输入并获得输出。发布实际异常,以便我们可以看到它何时发生。在support.py中,
total
是一个局部变量,其中调用了get\u sine\u length()
,即使我已将support.py导入stopping.py?我会把total定义为全局的吗?我的编辑有帮助吗?尽管它可以工作,但不要将total
作为全局变量;相反,运行get_sine_length
并将结果捕获到一个变量中。啊!我得到了它!非常感谢你!
>>> def func():
... localVar = "I disappear as soon as func() is finished running."
...
>>> print localVar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'localVar' is not defined
>>> func()
>>> print localVar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'localVar' is not defined