user3023787
user3023787

Reputation: 31

if else statement and dictionary in python

I just started programming. I am making a project where I count how many words occur in an article or a novel and the program prints the word and how many times it is repeated in the article. I use dictionaries in the program.

After that, i prompt the user to insert a word and the program will attempt to find how many times that word occurred if any. However, I have a problem with my last else statement. If the word does not exist, the "print("the word does not exist in the file inserted")" is repeated again and again. How can I solve it so it only is printed once?

Here is my code:

from string import * 
import codecs

def removePunctuation(sentence):

    new_sentence = ""
    for char in sentence:
        if char not in punctuation:
            new_sentence = new_sentence + char
    return new_sentence

def wordFrequences(new_sentence):
    wordFreq = {}
    split_sentence = new_sentence.split()
    for word in split_sentence:
        wordFreq[word] = wordFreq.get(word,0) + 1
    wordFreq.items()
    return (wordFreq)

#=====================================================

def main():

    fileName = open("arabic.txt","r")

    #fileName = open("arabic.txt","r",encoding="utf-8")

    new_sentence = removePunctuation(fileName)
    D = wordFrequences(new_sentence)
    #print(D) 

    excel = open("file.csv", "w")
    excel.write("words in article" + "\t" + "frequency" + "\n\n")

    for i in D:
        #print(i , D[i])
        excel.write(i + "\t" + str(D[i]) + "\n")

    prompt = input("insert a word for frequency: ")


    found = True 
    for key in D:
        if key == prompt:
            print(key, D[key])
            break 

        else:
            print("the word does not exist in the file inserted")

main()

Upvotes: 3

Views: 2318

Answers (1)

abarnert
abarnert

Reputation: 365777

I should point out that you actually don't need this loop at all. The whole point of a dictionary is that you can look things up by key directly. So:

try:
    print(prompt, D[prompt])
except KeyError:
    print("the word does not exist in the file inserted")

But let's look at how to fix your existing code.

The problem is that you're doing the if/else once for each key in the dictionary, and printing that output every time any key fails to match, instead of only if no key fails to match.

You can fix this by using a for/else instead of an if/else:

for key in D:
    if key == prompt:
        print(key, D[key])
        break 

else:
    print("the word does not exist in the file inserted")

This way, the else only triggers if you get through the whole loop without hitting a break, instead of triggering each time through the loop that you don't break.

This is a tricky concept for some people to get at first (especially people coming from other languages that don't have this feature), but the tutorial section break and continue Statements, and else Clauses on Loops explains it pretty well.


Alternatively, you have that Found flag; you could actually use it:

found = False
for key in D:
    if key == prompt:
        print(key, D[key])
        found = True
        break 
if not found:
    print("the word does not exist in the file inserted")

However, that's more code, and more places to get something wrong.

Upvotes: 5

Related Questions