1

I try to understand, in this code, why python print the letter "w"? (I work with python 2.7.8):

LetterNum = 1

for Letter in 'Howdy!':
    if Letter == 'w':
        pass
        print 'Encountered w, not processed.'
    print ('Letter', LetterNum, 'is', Letter)
    LetterNum+= 1

I get this result:

>>> 
('Letter', 1, 'is', 'H')
('Letter', 2, 'is', 'o')
Encountered w, not processed.
('Letter', 3, 'is', 'w')
('Letter', 4, 'is', 'd')
('Letter', 5, 'is', 'y')
('Letter', 6, 'is', '!')

While I thought I should get this result:

>>> 
('Letter', 1, 'is', 'H')
('Letter', 2, 'is', 'o')
Encountered w, not processed.
('Letter', 4, 'is', 'd')
('Letter', 5, 'is', 'y')
('Letter', 6, 'is', '!')
>>>  
1
  • If you need to keep track of index / loop number in a for loop, you should use enumerate. So you would use for LetterNum, Letter in enumerate('Howdy!'): Note though that this is zero-indexed by default. Commented Jul 7, 2015 at 13:24

2 Answers 2

5

You are trying to use pass as though it were continue. Pass does nothing, while continue skips the current iteration. Here is code that does what you want with correct usage of continue:

LetterNum = 1

for Letter in 'Howdy!':
    if Letter == 'w':
        print 'Encountered w, not processed.'
        continue
    print ('Letter', LetterNum, 'is', Letter)
    LetterNum+= 1
Sign up to request clarification or add additional context in comments.

Comments

0

I hope you get the logical error in the code through @DanDoe's answer.
But if you just want the required output , an alternate solution would be to use else statement.

LetterNum = 1
for Letter in 'Howdy!':
    if Letter == 'w':
        print 'Encountered w, not processed.'
    else:
        print ('Letter', LetterNum, 'is', Letter)
        LetterNum+= 1

This would improve the efficiency of the code.

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.