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

时间:2016-03-11 22:58:15

标签: python list

以下是我的代码片段:

# 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'类型。

2 个答案:

答案 0 :(得分:1)

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

请记住,函数在遇到return语句时会返回。

你可以这样编写你的函数:

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

答案 1 :(得分:0)

第一次测试时你return False。如果我要问"你是10岁,12岁,25岁还是30岁之一?"你可以测试一下,"我是10岁?" "否&#34 ;. "我不是其中之一。"这没有意义。你需要走到最后:

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