Home > Net >  if-else statement not working correctly in python for loop
if-else statement not working correctly in python for loop

Time:11-24

I have a block of code that I am iterating through a dictionary looking for keywords found and the number of times each is found. The if statement works and returns the expected output if keywords are found. However, the else statement is not working when no keywords are found it should return "No keywords found". This seems simple enough but I just can't put my finger on why this is not working. I'm fairly new to coding, so I apologize if this seems extremely basic.

Here is the code block I'm using:

    with open(keyword_file_path, 'r') as file:
        data = file.read()

    kw_found = {}
    for keyword in keywords:
        found = re.findall(keyword, data, re.I)
        if found:
            kw_found[keyword] = len(found)

    for key in kw_found.keys():
        if key in kw_found.keys():
            width = max(len(x) for x in key)
            output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key]))
        else:
            output_fp.write("No Keywords Found\n")

The if statement works and we get the following output if it does find the predefined keywords:

dog : 5

cat : 2

bird : 100

What should happen when it does not find the keywords is return "No Keywords Found"; however, it just doesn't return anything. No errors are reported, so it seems it just never sees the else statement as True if I'm understanding it correctly.

Any advice to get this to work would be greatly appreciated! Thank you in advanced!

CodePudding user response:

    for key in kw_found.keys():

The above line will go through each element of kw_found.keys(), binding them to key.

        if key in kw_found.keys():

This asks if the thing we're looking at from kw_found.keys() is in kw_found.keys() - which, yes, it is.

            width = max(len(x) for x in key)
            output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key]))

This next line will never fire. If kw_found.keys() is empty, the block it's in will never fire.

        else:
            output_fp.write("No Keywords Found\n")

CodePudding user response:

The observed behavior is correct. In your code, you are iterating over all detected keywords, which are stored in kw_found. And then you are checking if the current keyword is part of the dictionary you are iterating through. And this is always true.

  • Related