4

I have a statement like this

for word in tweet_text:
    if word in new_words:
        if new_words[word] == 0:
             new_words[word] = sent_count
        else:
             new_words[word] = (new_words[word] + sent_count) / 2

And I am very suspicious that the else block is executed every time when the first condition is not met (if word in new_words), is this possible?Am I am doing something wrong with indentication?

5
  • That seems fine to me...what are new_words and tweet_text, dictionaries? Commented May 8, 2013 at 20:30
  • Scope in Python is determined by identation, and I think your code wouldn't even run if you mixed spaces with tabs... Are you really sure about what you're saying? Have you debugged your code? Commented May 8, 2013 at 20:31
  • Yes, the point is that I get KeyError in else block but it should never happen because of first condition Commented May 8, 2013 at 20:31
  • I think your mistake is in your maths - are you trying to average the number of each word? Commented May 8, 2013 at 20:33
  • Yeah, it looks like an inconsistent indentation error (mixed tabs and spaces). Run your code with python -tt your_program_name.py to verify this, and then switch to four-space tabs. Commented May 8, 2013 at 20:38

1 Answer 1

9

The else clause corresponds to the if on the same level of indentation, as you expect.

The problem you see may be due to the fact that you are mixing tabs and spaces, so the apparent level of indentation is not the same as the one your interpreter sees.

Change all tabs into spaces and check if the problem goes away.

Sign up to request clarification or add additional context in comments.

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.