【问题标题】:Python 3 - Unable to increment global variable inside functionPython 3 - 无法在函数内增加全局变量
【发布时间】:2021-11-13 08:45:56
【问题描述】:

我在技术评估中遇到问题。基本代码(已编写)看起来像这样。

count=0

def findthesum(a,n):
    global count
    sum=0
    
    '''
    write your code here
    '''
    
    return sum
            
def main():
    global count
    n=5
    a=[1,2,3,4,5]
    print(count)
    print(findthesum(a,n))
    
main()

我必须在代码中的指定位置编写我的逻辑。我的代码看起来像这样。

count=0

def findthesum(a,n):
    global count
    sum=0
    l=[]
    for i in range(31):
        l.append(2**i)

    for j in range(n):
        if(a[j] in l):
            count=count+1
            sum=sum+a[j]
    return sum
            
def main():
    global count
    n=5
    a=[1,2,3,4,5]
    print(count)
    print(findthesum(a,n))
    
main()

即使在声明为全局变量后,我也无法增加 count 变量的值。

这是什么问题以及如何解决这个问题?

【问题讨论】:

  • 查看答案后,我意识到在main函数中我在调用findthesum函数之前打印了count变量,所以打印的是0。count变量实际上是在函数内部递增的。跨度>

标签: python python-3.x scope global-variables global


【解决方案1】:
count=0

def findthesum(a,n):
    global count
    sum=0
    
    for i in range(n):
        sum+=a[i]
        count+=1
        print(count, end= '')

    print(f'  The sum is: ' + str(sum)) 
            
def main():
    global count
    n=5
    a=[1,2,3,4,5]
    print(count)
    print(findthesum(a,n))
    
main()

--> '12345  The sum is: 15'

【讨论】:

    【解决方案2】:

    您是否要对所有元素求和?如果是,那么:

    count=0
    a=[1,2,3,4,5]
    n=5
    def counting(li, le):
        for i in range(le):
            try:
                count+=li[i-1]
        except:
            pass
        else:
            pass
        return count
    counting(a, n)
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多