Here is the question:
Write a program to accept 2 inputs from user, a string and a list of letters. It should then display True if the entered string consists of all the letters in a given list.
And here is the solution I wrote:
def guess(secword,thelist):
for letter in thelist:
if letter not in secword:
return False
return True
word=str(input("Please enter a word"))
print("The length of your word is",len(word))
aList=[]
for i in word:
x=input("Please enter a character to add to the list")
aList.append(x)
print(aList)
print(guess(word,aList))
This solution I wrote works, however, if I change the code as such (adding an else statement):
def guess(secword,thelist):
for letter in thelist:
if letter not in secword:
return False
else:
return True
It does not work anymore.
Can anyone please provide an explanation? Thanks for your time
CodePudding user response:
Any return statement ends the function right there. In your broken code example
def guess(secword, thelist):
for letter in thelist:
if letter not in secword:
return False
else:
return True
(which is a quite typical beginner's gotcha) you return from the first iteration og the loop in every case. That means you are only examining the first element of the thelist
.
def guess(secword, thelist):
for letter in thelist:
if letter not in secword:
return False
return True # you only know for sure after all are examined
CodePudding user response:
def guess(secword,thelist):
for letter in thelist:
if letter not in secword:
return False
else:
return True
Think about what this is doing; it will check the first letter of the list, and if that letter is not present in secword it will correctly return false. If the letter is in secword, however, it will return true instantly without checking the rest of the letters in the word. If I understand the question correctly, your initial function should be correct. That one will return false if any letter in the list is not in the word, and true otherwise.
CodePudding user response:
Putting the "return True" inside the for-loop changes how it will work compared to the first solution. It will just check the first letter and return either False or True and exit from the function without looking at the rest of the letters.