Home > Software engineering >  How to get only one else statement for nested if/else statements inside for loop in python?
How to get only one else statement for nested if/else statements inside for loop in python?

Time:10-20

enter image description here

I want to get the else statement only if there is no word from the spam_word list matches the data.

CodePudding user response:

This was rewritten from your image, but the premise is to check your counter after the for loop.

If one hit is enough from the data, you could also "break" from the "for words in data" loop

count = 0
for word in spam_word:
    if word in data:
        print(word)
        count  = 1

# after the for loop check if words were found
if count:
    # words found
    print("Spam word found ",count)
else:
    # words not found
    print("Email does not include any predefined spam words.")

CodePudding user response:

How about swapping the if condition: . . .

if word not in data:
    print("Email does not include any predefined spam words.")
else:
    print(word)
    count  = 1

. . .

  • Related