0

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
1
  • What is your actual output? Commented Apr 10, 2015 at 5:26

3 Answers 3

4

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')
Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.