列表,函数,循环,if/else/elif语句

2024-10-03 09:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的代码片段:

# custom function checkValid
def checkValid(chooseGenre):

    # create a list of valid genres
    genres = ["house" , "trance" , "techno" ]
    for genre in genres :
        if chooseGenre == genre :
            return True
        else:
            return False

#--------------------------------------------------------------------
while True :

    # prompt user to specify what genre of music they want to choose and save into a variable  
    chooseGenre = input("Which of the following genres of electronic dance music would you like to choose? ")

    # the user chooses a valid genre
    if checkValid(chooseGenre) == True :


        # user chooses house
        if (chooseGenre == "house") :
            edmMusic = genreHouse()

        # user chooses trance
        elif (chooseGenre == "trance") :
            edmMusic = genreTrance()

        # user chooses techno
        elif (chooseGenre == "techno") :
            edmMusic = genreTechno()               

        break 

    else :

        # user chooses an invalid genre
        print("Not a valid genre. Please try again. ")

我很难将“techno”和“trance”这两种类型识别为有效类型。这两种类型的输出是

"Not a valid genre. Please try again. "

我不明白为什么只接受'house'体裁。你知道吗


Tags: oftotrueifhousegenresvaliduser
2条回答

你在第一次考试时return False。如果我问“你是10岁、12岁、25岁还是30岁?”你可以测试,“我10岁吗?”“不”我不是那种人。”那没道理。你需要走到最后:

for genre in genres:
    if chooseGenre == genre:
        return True
return False # We don't get to this point unless all of them were False.

不过,有一种更简单的方法:

return chooseGenre in genres

错误在于函数checkValid。您要做的是执行成员资格测试,但实际上您要做的是查看列表的第一项["house" , "trance" , "techno" ],然后返回True(如果您的函数参数是'house'),否则返回False。你知道吗

请记住,函数遇到return语句时将永远返回。你知道吗

您可以这样编写函数:

def checkValid(chooseGenre):
    return chooseGenre in {'house', 'trance', 'techno'}

相关问题 更多 >