4

コードを実行するたびに、合計が定義されていないことがわかります。support.pyで定義し、stopping.pyにインポートします。私は似たようなケースを探しましたが、なぜそれが私にこれを言っているのかわかりません。助けてください!

これはstopping.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)
4

1 に答える 1

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

関数は、特定の入力を受け取り、他の入力を出力するマシンと考えてください。通常、マシンを開く必要はありません。入力を入力して出力を取得するだけです。

于 2012-10-20T00:07:30.167 に答える