lel
lel

Reputation: 41

while loop not generating output

what is the problem with the following code:

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

expected output:

2011.txt
2011.txt
2011.txt

Upvotes: 0

Views: 74

Answers (3)

John La Rooy
John La Rooy

Reputation: 304167

When the if condition is false you are not incrementing i

dedent the last line like this.

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

It's better to just use a for loop though (say goodbye to "off-by-one" bugs)

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

If you also need a loop counter, use enumerate

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

Upvotes: 4

attaboyabhipro
attaboyabhipro

Reputation: 1648

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

Upvotes: 0

backtrack
backtrack

Reputation: 8144

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

You are not incrementing i when condition is false

use for or something like above

O/p 

2011.txt
2011.txt
2011.txt

Upvotes: 0

Related Questions