简单的循环混乱

0 python scope

我很困惑为什么以下代码(特别是for循环部分)没有按预期工作:

sum = 0

def numberofdays ():
    for i in range (1901, 2000):
        if i%4 == 0:
            sum = sum + 366
        else:
            sum = sum + 365


sum = sum + 365 #to account for year 2000.

print sum
Run Code Online (Sandbox Code Playgroud)

sum值返回365,但它应该返回1901年到2000年之间的总天数 - 远大于365的数字!

Eti*_*oël 5

sum在函数外部定义,而不是调用它.因此,sum = sum (0) + 365这在程序的眼中是正确的,但不是你想要的.你可能想要:

sum = 0

def numberofdays ():
    sum = 0
    for i in range (1901, 2000):
        if i%4 == 0:
            sum = sum + 366
        else:
            sum = sum + 365
    return sum


sum = numberofdays() + 365 #to account for year 2000.

print sum
Run Code Online (Sandbox Code Playgroud)

两个sum变量之间存在差异.它们是不同的!您可以在此处阅读变量范围.

另外,正如@Chris_Sprague所指出的,你应该更改sum的名称,因为它是一个内置函数.

这是一个更新版本:

n = 0

def numberofdays ():
    total = 0
    for i in range (1901, 2000):
        if i%4 == 0:
            total = total + 366
        else:
            total = total + 365
    return total 


n = numberofdays() + 365 #to account for year 2000.

print n 
Run Code Online (Sandbox Code Playgroud)