gpt4 book ai didi

赋值前引用的 Python 局部变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:38 26 4
gpt4 key购买 nike

我已经创建了一些代码:

 import numpy as np
Length=(2.7)*10**-3
Nx=4
x = np.linspace(0, Length, Nx+1) # mesh points in space
t1=110
t2=100
m=((t2-t1)/Length)
T=5
N=5
t = np.linspace(0, T, N+1)
Coeff=0.5
b=0.2
tamb = 20
u = np.zeros(Nx+1)
u_1 = np.zeros(Nx+1)
for i in range(0, Nx+1):
u_1[i] = m*(x[i])+t1
#print u_1
r=[]
for n in range(0, N+1):
# Compute u at inner mesh points
for i in range(0,1):
u[i] = 2*Coeff*(u_1[i+1]+b*tamb)+(1-2*Coeff-2*b*Coeff)*u_1[i]
for i in range(1,Nx):
u[i] = Coeff*(u_1[i+1]+u_1[i-1])+(1-2*Coeff)*u_1[i]
for i in range(Nx,Nx+1):
u[i] = 2*Coeff*(u_1[i-1])+(1-2*Coeff)*u_1[i]
# Switch variables before next step
u_1, u = u, u_1
r.append(u.copy())
print r[5]

代码输出:

 [  78.1562   94.1595   96.82    102.6375  102.125 ]

使用代码我创建了一个应用于数组的函数:

def function(data,time):
import numpy as np
Values=data[n]
Length=(Values[2])*10**-3
Nx=4
x = np.linspace(0, Length, Nx+1) # mesh points in space
t1=Values[0]
t2=Values[1]
m=((t2-t1)/Length)
T=time[5]
N=5
t = np.linspace(0, T, N+1)
Coeff=0.5
b=0.2
tamb = 20
u = np.zeros(Nx+1)
u_1 = np.zeros(Nx+1)
for i in range(0, Nx+1):
u_1[i] = m*(x[i])+t1
#print u_1
r=[]
for n in range(0, N+1):
# Compute u at inner mesh points
for i in range(0,1):
u[i] = 2*Coeff*(u_1[i+1]+b*tamb)+(1-2*Coeff-2*b*Coeff)*u_1[i]
for i in range(1,Nx):
u[i] = Coeff*(u_1[i+1]+u_1[i-1])+(1-2*Coeff)*u_1[i]
for i in range(Nx,Nx+1):
u[i] = 2*Coeff*(u_1[i-1])+(1-2*Coeff)*u_1[i]
# Switch variables before next step
u_1, u = u, u_1
r.append(u.copy())
return r
import numpy as np

#arrays
data=np.array(((110,100,2.5),(112,105,2.6),(115,109,2.7)))
time=np.array((0,1,2,3,4,5))
#apply function to array
for n in range(len(data)):
r = function(data,time)
print r[5]

第一个代码工作正常,但是当我使用函数(第二个代码)应用代码时,如果我告诉我出现以下错误:

Traceback (most recent call last):
File "C:/Users/a/Desktop/functiontrial3.py", line 39, in <module>
r = function(data,time)
File "C:/Users/a/Desktop/functiontrial3.py", line 3, in function
Values=data[n]
UnboundLocalError: local variable 'n' referenced before assignment

我需要做什么才能使以下代码正常工作?

最佳答案

你在这里使用了全局的n

Values=data[n]

您在这里使用 n 作为局部变量

for n in range(0, N+1):

Python 不允许您在同一范围内将 n 用作全局和局部。

应该是相同的 n 还是只是对变量名的错误重用?

有多种方法可以修复此错误,但这取决于您的意图。

关于赋值前引用的 Python 局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16888381/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com