def song():
print("Wellcome The Song Game")
newfile = open("songs.txt","r")
sangg_2D = eval(newfile.read())
newfile.close()
sang2 = sangg_2D[0:11]
print("The Song Name Is", sang2)
sangg3 = input("Name The Song")
found = False
for count in range(len(sangg_2D)):
if sangg3 == sangg_2D[count][0]:
score = score + 2
found = True
#score = score+2
print("welldone You Got The Answer Correct On Your First Try")
else:
if found==False:
print("Wrong Answer Try Again")
song()
song()
它会打印文件中的每个单词,而我只希望它打印歌曲艺术家和一点名字
歌曲名称为[['j.cole','MIDDLE CHILD'],['Mustard','Pure 水”],['Khalid','Talk'],['Cardi B','Please Me'],['Beyoncé', '在我放手之前'],['导航','价格在我头上'],['克里斯·布朗', [回到爱情]],[[法国蒙大拿州],[幻灯片],[[贾斯汀·贝伯],[我] 不在乎”,['Ari Lennox','鲜奶油']
答案 0 :(得分:0)
根据您的问题和源代码,我能理解的是,您想获取一首歌曲名称,并让用户找到该歌曲名称的正确歌手。如果是这种情况,则可以大大简化代码:
import random
def song():
score = 0
print("Wellcome The Song Game")
newfile = open("songs.txt","r")
sangg_2D = eval(newfile.read())
newfile.close()
randomSong = random.randint(0,len(sangg_2D)-1)
found = False
while not found:
sang2 = sangg_2D[randomSong][1]
print("The Song Name Is", sang2)
sangg3 = input("Name The Artist")
if sangg3 == sangg_2D[randomSong][0]:
score = score + 2
found = True
print("welldone You Got The Answer Correct On Your First Try")
break
else:
print("Wrong Answer Try Again")
song()
首先,您阅读文件的内容以获取所有艺术家及其各自的歌曲。顺便说一下,最好使用ast.literal_eval
模块中的ast
,而不是eval
。然后,您从列表中选择一首随机歌曲,并让用户猜测正确的歌手。如果用户找到艺术家,则您的程序已完成,否则它将再次要求用户猜测艺术家。您还需要在第一次尝试时用score
来修复该零件,因为无法检查用户是否在第一次尝试中找到了它。