【发布时间】:2019-07-03 19:26:32
【问题描述】:
我在学校做一个项目,要求我用 python 做一个音乐测验,它读取一个文件,显示歌曲每个单词的第一个字母和艺术家(例如 Dave F F)。在我的文件中,我有一个包含 10 个歌曲名称的列表,其中 python 获取随机行并进行显示。它必须来自一个文件(我的是记事本) 用户必须有 2 次机会猜测歌曲的名称,如果没有,则游戏结束。我遇到的问题是我无法让我的代码问另一个问题,并存储最后一个问的问题,这样它就不会再问了(例如,如果第一个问题是 Dave 和 FF,我希望它不再出现) .如果有人向我展示如何让 python 显示排行榜,我也将不胜感激。可以回答请是完整的代码,因为我不擅长缩进并将代码放在正确的位置。
我已经给了用户 2 次正确播放歌曲的机会,如果他们不正确,则程序结束,但不会循环到开头。
import random
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
random_song, random_artist = random.choice(songs_and_artists)
songs_intials = "".join(item[0].upper() for item in random_song.split())
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
nb_tries_left = 3
guess = input("Guess the name of the song! ")
nb_tries_left -= 1
finished = False
while not finished:
answer_found = (guess == random_song)
if not answer_found:
guess = input("Nope! Try again! ")
nb_tries_left -= 1
elif answer_found:
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
finished = (answer_found or nb_tries_left <= 0)
if answer_found:
歌曲的首字母是 LT,艺术家的名字是 Fredo 猜歌名!像那样 歌曲的首字母是 LT,艺术家的名字是 Fredo 干得好!
Python 不会再问另一个问题,我不知道它是否会再次出现这样的问题。
故意弄错会输出这个:
The songs' initials are CS and the name of the artist is 50 Cent
Guess the name of the song! candysong
Nope! Try again! carpetshop
Nope! Try again! coolsong
Sorry, you've had two chances. Come back soon!
>>>
【问题讨论】:
标签: python file loops leaderboard