无法理解局部和全局变量

2024-09-27 02:25:39 发布

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

作为一名新的python学习者,我非常感谢您的建议,为什么我对以下案例的理解是错误的:

当我编写如下代码时:

class Solution(object):

    def isHappy(self, n):
        seen = {}
        while n!=1 and n not in seen.keys():
            seen[n] = '*'
            n = self.get_next(n)
        return n==1

    total_sum = 0
    def get_next(self,no):

        while no>0:
            no,v = divmod(no,10)
            total_sum+=v**2
        return total_sum
test55 = Solution()
test55.isHappy(56)

但是它给了我一个错误,说“赋值前引用的局部变量'total\u sum',我认为它应该工作,因为:虽然我们没有在get\u next函数内初始化total\u sum,但我希望它应该在函数外查找total\u sum。有谁能告诉我为什么我错了

如果我们把total\u sum放在get\u next函数中,那么它就起作用了:

class Solution(object):

    def isHappy(self, n):
        seen = {}
        while n!=1 and n not in seen.keys():
            seen[n] = '*'
            n = self.get_next(n)
        return n==1


    def get_next(self,no):
        total_sum = 0
        while no>0:
            no,v = divmod(no,10)
            total_sum+=v**2
        return total_sum
test55 = Solution()
test55.isHappy(56)

Tags: 函数noselfgetreturndef错误next

热门问题