while循环不产生输出

while loop not generating output

以下代码有什么问题:

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
while i < len(years):
    if a.endswith(years[i] + '.txt'):
        print(years[i] + '.txt')
        i += 1

预期输出:

2011.txt
2011.txt
2011.txt

if 条件为假时,您不会递增 i

像这样缩进最后一行。

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
while i < len(years):
    if a.endswith(years[i] + '.txt'):
        print(years[i] + '.txt')
    i += 1

最好只使用 for 循环(告别 "off-by-one" 错误)

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
for item in years:
    if a.endswith(item + '.txt'):
        print(item + '.txt')

如果您还需要循环计数器,请使用enumerate

a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
for i, item in enumerate(years):
    if a.endswith(item + '.txt'):
        print(item + '.txt')
a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
for i in years:
    if a.endswith(i + '.txt'):
        print(i + '.txt')

当条件为假时,您不会递增 i

使用for或类似上面的东西

O/p 

2011.txt
2011.txt
2011.txt
a = '2011.txt'
years = ['2011', '2011', '2011', '2012', '2013']
i = 0
while i < len(years):
    if a.endswith(years[i] + '.txt'):
        print(years[i] + '.txt')
    i += 1