NameError: the global name "total" is not defined, but it

Every time I run my code, it tells me that the amount is undefined. I defined it in the support.py file, which is then imported into stopping.py. I have searched for similar cases, but I do not understand why this tells me this. Please, help!

This is 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() 

This is 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
source share
1 answer

total is local to get_sine_length . Since you return it to get to it, you call get_sine_length and save the result.

The problem actually has nothing to do with import . It would be the same if the function definition for get_sine_length was in stopping.py . Variables defined inside functions (inside def someFunc(): are available only for this function, unless you force them to be global. However, most of the time you should not declare global variables just to access normally local vars from outside the function - this is what is returned for.

This example shows the general problem you are facing. I hesitate to call it a problem, because it is actually an important language function of python (and many other programming languages).

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

Think of a function as a machine that accepts certain inputs and outputs others. Usually you do not want to open the machine - you just want to insert the input and get the result.

+5
source

Source: https://habr.com/ru/post/1440899/


All Articles