Python Forum
A function that takes a word and a string of forbidden letters - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: A function that takes a word and a string of forbidden letters (/thread-19079.html)



A function that takes a word and a string of forbidden letters - pooyan89 - Jun-12-2019

Hi I have a question:
Write a function named avoids that takes a word and a string of forbidden letters, and that returns True if the word doesn’t use any of the forbidden letters.

The solution is :
def avoids(w,l):
    for j in w:
        if j in l:
            return False
    return True
I know I can write this code in other ways as well but when I write :


def avoids2(w,l):
    for i in w:
        if i not in l:
            return True
    return False
I get True every time!
avoids('word','o') gives me False which is correct!
avoids2('word','o') gives me True which is not correct!
WHY the avoids2 is not working correctly?


RE: A function that takes a word and a string of forbidden letters - Yoriz - Jun-12-2019

The loop stops straight away because w is not in 'o' so it returns True.


RE: A function that takes a word and a string of forbidden letters - pooyan89 - Jun-12-2019

(Jun-12-2019, 07:12 PM)Yoriz Wrote: The loop stops straight away because w is not in 'o' so it returns True.

But it is not so in the first case. Can you explain more ?!


RE: A function that takes a word and a string of forbidden letters - Yoriz - Jun-12-2019

In the first case it is checking if w is in 'o' which it is not so it doesn't return False,
moves on the the next letter in the loop, o is in 'o' so returns False.


RE: A function that takes a word and a string of forbidden letters - pooyan89 - Jun-12-2019

(Jun-12-2019, 07:23 PM)Yoriz Wrote: In the first case it is checking if w is in 'o' which it is not so it doesn't return False,
moves on the the next letter in the loop, o is in 'o' so returns False.

OK I have to read the return chapter carefully this time! thank you for the help Blush


RE: A function that takes a word and a string of forbidden letters - nilamo - Jun-12-2019

As soon as you hit a return, the function is done and doesn't run through the rest of the for-loop. If you imagine a bus ride as a for loop, the return statement is like jumping off the bus before making it to the destination... you miss out on the rest of the bus ride.