NameError:未定义全局名称“total”,但它是

时间:2012-10-20 00:05:15

标签: python variables global

每次运行我的代码时,它都会告诉我未定义总计。我在support.py中定义了它,然后将其导入stops.py。我找了类似的案例,但我不明白为什么它告诉我这个。请帮忙!

这是stops.py

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)

1 个答案:

答案 0 :(得分:5)

total位于get_sine_length的本地。由于您要将其返回,因此请致电get_sine_length并存储结果。

问题实际上与import实际上没有任何关系。如果get_sine_length的函数定义在stopping.py中,则相同。函数内部定义的变量(def someFunc():内)只能被该函数访问,除非你强制它们是全局的。但是,大多数情况下,不应该声明全局变量只是为了从函数外部访问正常的本地变量 - 这就是返回的目的。

此示例显示了您遇到的一般问题。我对于将其称为问题犹豫不决,因为它实际上是python(以及许多其他编程语言)的重要语言特性。

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

将某个功能视为接收某些输入并输出其他功能的机器。您通常不想打开机器 - 您只想将输入放入并获得输出。