0

I have a function that checks if a given string is in a list of strings using a for and while loop. I’m not supposed to use the ‘in’ operator. Here’s my code using a for loop:

def word_in_list(words, word):
    for strings in words:
        if len(words) > 0 and strings == word:
            return True
        else:
            return False

However, it is not returning True unless the single string is the first element of the list. The list should return False in case the list is empty. And how can I solve the same problem using a while loop (and without 'in' operator)?

1
  • So you should not return false in the for loop. Put the statement return false after the for loop. The logic is that you return true if you find the word. Once for loop is finished without finding it, return false. Commented Jan 13, 2021 at 12:27

4 Answers 4

1

Don’t return False the moment you find one mismatch, return False when you are done checking all possibilities and not finding any match:

def word_in_list(words, word):
    for strings in words:
        if strings == word:
            return True
    return False

Also, no need to check the length of list every time, if it's zero, you don't run the loop at all and directly return False.

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

Comments

0

Your code is wrong because of the else statement. Your function must return False only after checking the whole list, not just the first element. Whenever a function gets to a "return" instruction, it stops, so it just checked the first one. This is the correct solution:

def word_in_list(words, word):
    i = 0
    while i < len(words):
        if words[i] == word:
            return True
        i += 1
    return False

Comments

0

simly use this code

def word_in_list(words, word):
    if word in words:
       return True
    else
       return False

2 Comments

in is not allowed to be used as per OP's condition. And you are using in, directly doing return word in words is enough.
On the other hand the question states, that a for loop should be used and you can't write a for loop withot ` in`.
0

Your else block kicks-in without finishing the iteration on complete list.

def word_in_list(list_of_words, word_to_search):
    found = False
    for word in list_of_words:
        if word == word_to_search:
            found = True
            break # breaks iff the word is found
    return found 

Any particular reason you are adamant not to use the 'in' operator? Also, please be careful about the indentation in the code you paste.

1 Comment

Thank you!! The exercise is strictly about loops, otherwise it would have been easier haha

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.