以下是我的代码片段:
# 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'
类型。
答案 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