Help with Python UnboundLocalError: local variable referenced before assignment

后端 未结 4 1758
Happy的楠姐
Happy的楠姐 2021-01-14 23:53

I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am

相关标签:
4条回答
  • 2021-01-15 00:28

    where do you call force in this code?

    In any event, the problem is in update_r. You reference vs in the first line of update_r even though vs is not defined in this function. Python is not looking at the vs defined above. Try adding

    global vs
    

    as the first line of update_r or adding vs to the parameter list for update_r

    0 讨论(0)
  • 2021-01-15 00:32

    In the first line of update_r, you have vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe). Look at the function that you are calling. You are calling update_v with a bunch of parameters. One of these parameters is vs. However, that is the first time in that function that vs appears. The variable vs does not have a value associated with it yet. Try initializing it first, and your error should disappear

    0 讨论(0)
  • 2021-01-15 00:37

    Put an additional global statement containing all your globals after each def statement. Otherwise, all globals are transformed into locals within your def without it.

    def update_v(n,vs,ve,ms,me,dt,fs,fe):
        global vs, ve, ...  
    
    0 讨论(0)
  • 2021-01-15 00:37

    On line 39 you do

    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
    

    while you are inside a function. Since you defined a global variable called vs, you would expect this to work. It would have worked if you had:

    vs_new,ve_new = update_v(n,vs,ve,ms,me,dt,fs,fe)
    

    because then the interpreter knows vs in the function arguments is the global one. But since you had vs in the left hand side, you created an uninitialized local variable.

    But dude, you have a much bigger problem in your code: update_r calls update_v, update_v calls force, and force calls update_r - you will get a stack overflow :)

    0 讨论(0)
提交回复
热议问题