我很困惑为什么以下代码(特别是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
sum
值返回365,但应返回1901年到2000年之间的总天数 - 这个数字远大于365!
答案 0 :(得分: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
两个sum
变量之间存在差异。它们是不同的!您可以阅读变量范围here。
另外,如@Chris_Sprague所述,您应该更改sum的名称,因为它是built-in function。
以下是更新版本:
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
答案 1 :(得分:2)
试试这个:
mySum = 0
def numberofdays ():
global mySum # fix scope issues
for i in range (1901, 2001): # fix Y2K (index) issue
if i%4 == 0:
mySum = mySum + 366
else:
mySum = mySum + 365
mySum = numberofdays()
print(mySum)
我对已提交的其他2个答案的补充是,您不应该调用变量sum
,因为它是built-in function in Python。
这是一种(主观)更好的方法,可以避免全局变量并使代码更灵活:
# NOTE: does not include endYear in the calculation
def numberOfDays(startYear, endYear):
sumOfDays = 0
for yearNum in range(startYear, endYear):
if yearNum % 4 == 0:
sumOfDays += 366
else:
sumOfDays += 365
return(sumOfDays)
myNumberOfDays = numberOfDays(1901, 2001)
print(str(myNumberOfDays))
答案 2 :(得分:1)
这是变量范围的问题。您的函数无法更改在其外部声明的变量sum
(尽管它可以读取其值)。试试这个:
sum = 0
def numberofdays ():
global sum
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
答案 3 :(得分:0)
你总是可以使用while循环; p
def numberofdays ():
a=0
c = 1901
while True:
if c < 2001:
c+=1
a += 365
continue
else:
print('The number if days between 1901 and 2000 is ',a )
break
numberofdays()