迭代写闰年
all_year = iter(range(2020))all_leapyear = []
while True:
i = next(all_year)
if i%4==0:
if i%100!=0:
all_leapyear.append(i)
if i == 2020:
all_leapyear.append(i)
break
LeapYear = iter(all_leapyear)
leapyear = LeapYear()
for i in leapyear:
if i == 2020:
print(i)
break
else:
print(i)
报错
Traceback (most recent call last):
File "C:\Users\chenh\Desktop\实验.py", line 4, in <module>
i = next(all_year)
StopIteration
为什么会报错 range(2020) 不包括 2020,所以应该 range(2021):
all_year = iter(range(2021))
all_leapyear = []
while True:
i = next(all_year)
if i%4==0:
if i%100!=0:
all_leapyear.append(i)
if i == 2020:
all_leapyear.append(i)
break
LeapYear = iter(all_leapyear)
leapyear = LeapYear()
for i in leapyear:
if i == 2020:
print(i)
break
else:
print(i)
两个错误:
第一个 range(2020) 不包含 2020 使得 i 不可能等于 2020 导致 next() 最后一次时候迭代器已经为空,抛出错误
第二个错误就是 leapyear = LeapYear() ,这段代码去掉,因为 LeapYear = iter(all_leapyear) 已经是一个迭代器了,你将 LeapYear() 进行调用会导致报错的
参考代码:
all_year = iter(range(2021))
all_leapyear = []
while True:
i = next(all_year)
if i%4==0:
if i%100!=0:
all_leapyear.append(i)
if i == 2020:
all_leapyear.append(i)
break
LeapYear = iter(all_leapyear)
for i in LeapYear:
if i == 2020:
print(i)
break
else:
print(i) zltzlt 发表于 2020-8-10 07:57
range(2020) 不包括 2020,所以应该 range(2021):
{:10_266:},代码还有一个错误 Twilight6 发表于 2020-8-10 08:01
,代码还有一个错误
{:10_245:}
页:
[1]