猿问

为什么添加代码的后半部分后执行会发生变化?

我在编写用于测试pangram(至少包含一次所有26个字母表的字符串)的代码时遇到了困难。


当基于第一部分执行时,如下所示:


def ispangram(x):

    alphabet="abcdefghijklmnopqrstuvwxyz"

    for i in alphabet:

        if i in x.lower():

            return True

代码工作正常。


但是如果我添加 else 条件:


def ispangram(x):

    alphabet="abcdefghijklmnopqrstuvwxyz"

    for i in alphabet:

        if i in x.lower():

            return True

        else i not in x.lower():

            return False

该代码将每个输入作为有效的全图返回。


有人可以帮我了解这里出了什么问题吗?


沧海一幻觉
浏览 100回答 2
2回答

白板的微信

您没有检查字母表中的每个字母。您只检查单词是否包含字母 。让我们检查控制流adef is_pangram(x):    x = x.lower()    alphabet="abcdefghijklmnopqrstuvwxyz"    # we begin iteration here    for i in alphabet:        # we check if the letter is in the word        if i in x:            # we return! This will stop execution at the first True            # which isn't always the case            return True        else:            # we return again! since we've covered all cases, you will            # only be checking for a            return False要解决此问题,您可以执行以下两项操作之一。使用循环,您可以只检查字母是否不在 中,如果字母不在,则返回,并在末尾返回:xFalseTruedef is_pangram(x):    x = x.lower()    alphabet="abcdefghijklmnopqrstuvwxyz"    for i in alphabet:        if i not in x:            return False    # this means we made it through the loop with no breaks    return True或者,您可以使用运算符检查字母表中的所有字母是否都在单词中,该单词返回 ,否则返回allTrueFalsedef is_pangram(x):    x = x.lower()    alphabet="abcdefghijklmnopqrstuvwxyz"    return all(i in x for i in alphabet)

HUX布斯

对于包含任何字母的任何字符串,第一个函数将返回 true。您需要验证每个字母是否都在输入字符串中:import stringdef ispangram(x):    x = x.lower()    for c in string.ascii_lowercase:        if c not in x:            # a letter is not in the input string, so the input string is not a pangram            return False    # if we got here, each letter is in the input string    return True
随时随地看视频慕课网APP

相关分类

Python
我要回答