nameError: name 'pivots' 未定义

时间:2021-01-07 13:31:00

标签: module global-variables jupyter

您能帮我解决以下问题吗? 我确实在 pyhton 中编写了一个模块。对于下一个模块,我需要以下变量或值: lastprice 和 lastpivotprice

需要什么定义或脚本更改,这两个变量是全局变量)?

实际上,如果我尝试在模块外调用 lastpivotprice,则会收到以下错误消息: nameError: name 'pivots' 未定义

模块代码:checkpivots.py

    try:  
      df['High'].plot(label='high')

      pivots =[]
      dates = []
      counter = 0
      lastPivot = 0

      Range = [0,0,0,0,0,0,0,0,0,0]
      daterange = [0,0,0,0,0,0,0,0,0,0]

      for i in df.index:
        currentMax = max(Range , default=0)
        value=round(df["High"][i],2)
        Range=Range[1:9]
        Range.append(value)
        daterange=daterange[1:9]
        daterange.append(i)

      if currentMax == max(Range , default=0):
          counter+=1
      else:
          counter = 0
      if counter ==  5:
          lastPivot=currentMax
          dateloc =Range.index(lastPivot)
          lastDate = daterange[dateloc]

          pivots.append(lastPivot)
          dates.append(lastDate)
   
            
    except Exception:
      print("-")

    lastpivotprice = pivots[-1]
    
    lastprice=df.iloc[-1]['Close'] #read value in the last row in col 'close'
    lastprice2 = df['Close'].values[-2] #read value in the last row minus2 in col 'close'
   
    #print (lastprice)        
    # print (lastpivotprice)
    # print (lastprice2)

1 个答案:

答案 0 :(得分:0)

如果要将每个模块中的变量作为全局变量,则必须将它们设置为全局变量。例如,请参阅下面的代码:

c = 0 # global variable

def add():
    global c
    c = c + 2 # increment by 2
    print("Inside add():", c)

add()
print("In main:", c)

如果从 c 中删除 global,则 MAIN 中的 c 仍为 0。