Local variable 'first' referenced before assignment

This question already has an answer here:

  • Using global variables in a function other than the one that created them 18 answers

  • Python scans a function body for any assignments, and if they aren't explicitly declared global , then it creates a local scope variable for that name. Because you assign to first in your reverse() function, and you haven't explicitly declared first to be global within that function's scope, python creates a local variable named first that hides the global one.

    It doesn't matter that the assignment comes after the comparison; python implicitly declares all local variables at the beginning of the function.

    To fix this you can declare first to be global within the reverse() function, but as others have said, globals should be avoided when possible.

    链接地址: http://www.djcxy.com/p/23894.html

    上一篇: 为什么+ =操作符不工作

    下一篇: 赋值前引用局部变量“第一个”