如何修复代码中“UnboundLocalError:赋值前引用的局部变量”dc?

2024-06-16 08:56:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在调用dc之前,我很难找到它被引用的确切位置。任何帮助都将不胜感激。代码取自https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/36461.pdf的第14页 但是手册中的代码有一些缩进错误。相关代码(据我所知):

    def DCcalc(self,dc0,mth):
        fl = [-1.6, -1.6, -1.6, 0.9, 3.8, 5.8, 6.4, 5.0, 2.4, 0.4, -1.6, -1.6]
        t = self.t
        if(t < -2.8):
            t = -2.8
        pe = (0.36*(t+2.8) + fl[mth-1] )/2
        if pe <= 0.0:
            pe = 0.0
        if (self.p > 2.8):
            ra = self.p
            rw = 0.83*ra - 1.27 #*Eq. 18*#
            smi = 800.0 * math.exp(-dc0/400.0) #*Eq. 19*#
            dr = dc0 - 400.0*math.log( 1.0+((3.937*rw)/smi) ) #*Eqs. 20 and 21*#
            if (dr > 0.0):
                dc = dr + pe
        elif self.p <= 2.8:
            dc = dc0 + pe
        return dc

我的错误是:

UnboundLocalError                         Traceback (most recent call last)
<ipython-input-3-c2d03971ed28> in <module>
    140         infile.close()
    141         outfile.close()
--> 142 main()

<ipython-input-3-c2d03971ed28> in main()
    129             ffmc = round(fwisystem.FFMCcalc(ffmc0),2)
    130             dmc = round(fwisystem.DMCcalc(dmc0,mth),2)
--> 131             dc = round(fwisystem.DCcalc(dc0,mth),2)
    132             isi = round(fwisystem.ISIcalc(ffmc),2)
    133             bui = round(fwisystem.BUIcalc(dmc,dc),2)

<ipython-input-3-c2d03971ed28> in DCcalc(self, dc0, mth)
     87         elif self.p <= 2.8:
     88             dc = dc0 + pe
---> 89         return dc
     90     def ISIcalc(self,ffmc):
     91         mo = 147.2*(101.0-ffmc) / (59.5+ffmc)

UnboundLocalError: local variable 'dc' referenced before assignment

最后是main()函数:

def main():
    ffmc0 = 85.0
    dmc0 = 6.0
    dc0 = 15.0
    infile = open('c:Documents/data.txt','r')
    outfile = open('fwioutput.txt','w')
    try:
        for line in infile:
            mth,day,temp,rhum,wind,prcp,year=[float(field) for field in 
                                         line.strip().lstrip('[').rstrip(']').split()]
            if rhum>100.0:
                rhum = 100.0
            mth = int(mth)
            fwisystem = FWICLASS(temp,rhum,wind,prcp)
            ffmc = round(fwisystem.FFMCcalc(ffmc0),2)
            dmc = round(fwisystem.DMCcalc(dmc0,mth),2)
            dc = round(fwisystem.DCcalc(dc0,mth),2)
            isi = round(fwisystem.ISIcalc(ffmc),2)
            bui = round(fwisystem.BUIcalc(dmc,dc),2)
            fwi = round(fwisystem.FWIcalc(isi,bui),2)
            ffmc0 = ffmc
            dmc0 = dmc
            dc0 = dc
            outfile.write("%s %s %s %s %s %s\n"%(str(ffmc),str(dmc),str(dc),str(isi),str(bui),str(fwi)))
    finally:
        infile.close()
        outfile.close()
main()

Tags: inselfifmaindcinfilepestr