Py学习  »  Python

Python在简单函数中给出意外的返回值

Mandeep Singh • 4 年前 • 1729 次点击  

问题是:

编写一个程序来接受用户的两个输入,一个字符串和一组字母。如果输入的字符串由给定列表中的所有字母组成,则应显示True。

以下是我写的解决方案:

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))

但是,如果我更改代码(添加else语句),我编写的这个解决方案是有效的:

def guess(secword,thelist):
for letter in thelist:
    if letter not in secword:
        return False
    else:
        return True

它不再工作了。

有人能解释一下吗? 谢谢你抽出时间

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131656
文章 [ 3 ]  |  最新文章 4 年前