Python代码运行报NameError:weight未定义问题求助
NameError: name 'weight' is not defined even though I defined it in my function? Great question—this is a super common gotcha when you're just starting out with Python's variable scopes! Let's break this down clearly:
The Core Issue: Variable Scope + Uncaptured Return Values
In Python, variables defined inside a function (like your weight and i in grad_d()) are local to that function. That means they only exist while the function is running, and you can't access them directly from outside the function's code block.
Your function does return weight and i at the end, but you never saved those returned values to variables in the outer scope. When you try to run print('Weight: ', weight) outside the function, Python has no idea what weight you're referring to—hence the NameError.
Fixed Code + Additional Improvements
Here's your code with the key fixes, plus a couple of tweaks to avoid other potential errors:
import numpy as np from scipy import optimize as opt import time def grad_d(): # Use a numpy array instead of a list for smoother math operations weight = np.array([0, 0]) learnrate = 0.01 tol = 1.e-5 itmax = 1000 for i in range(itmax): deltaweight = - learnrate * opt.rosen_der(weight) weight = weight + deltaweight # Fix: deltaweight is an array—use norm to check convergence (not abs + learnrate) if np.linalg.norm(deltaweight) < tol: break return weight, i # Capture the function's return values in outer-scope variables final_weight, total_iterations = grad_d() print('Weight: ', final_weight) print('Iterations: ', total_iterations)
What Changed?
- Captured Return Values: We now assign the values returned by
grad_d()tofinal_weightandtotal_iterations, which are accessible outside the function. - Numpy Array for
weight: Your originalweight = [0, 0]is a regular list, which can cause issues when doing math with numpy arrays (like the output ofopt.rosen_der()). Switching tonp.array([0, 0])fixes this. - Fixed Convergence Check:
abs(deltaweight)won't work becausedeltaweightis an array—this would return an array of element-wise absolute values, which can't be compared to a scalar. Usingnp.linalg.norm(deltaweight)calculates the magnitude of the array, which is the right way to check if your weight update is small enough to stop.
内容的提问来源于stack exchange,提问作者D K




