Python Forum
A function that takes a word and a string of forbidden letters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A function that takes a word and a string of forbidden letters
#1
Exclamation 
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?
Reply
#2
The loop stops straight away because w is not in 'o' so it returns True.
Reply
#3
(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 ?!
Reply
#4
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.
Reply
#5
(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
Reply
#6
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Searching for parts of a string or word Ulumulu 8 3,646 Mar-15-2021, 07:02 PM
Last Post: Ulumulu
  Homework advice - Boolean function, whole-word values musicjoeyoung 4 3,186 May-07-2020, 06:10 PM
Last Post: musicjoeyoung
  Trying to extract Only the capitol letters from a string of text Jaethan 2 2,135 Feb-27-2020, 11:19 PM
Last Post: Marbelous
  count unique letters in a word sunny_awesome 4 8,642 Jun-06-2019, 07:15 PM
Last Post: kotter
  Counting only letters in a string PraiseYAH 2 4,462 Jul-20-2018, 11:22 AM
Last Post: ichabod801
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,060 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020