如何使代码问另一个问题并存储最后一个

问题描述 投票:0回答:2

我做在学校一个项目,要求我做Python中的音乐测验,读取文件,显示歌曲的每一个字和艺术家(如戴夫·F F)的第一个字母。在我的文件我有10名歌曲的列表,其中蟒蛇取随机线和不显示。它必须是从一个文件(我的是记事本)的用户必须有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和艺术家的名字是弗雷猜歌曲的名字!像那样的歌曲的首字母是LT和艺术家的名字被弗雷干得好!

然后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
2个回答
0
投票

首先你要得到两个独特的歌曲。要做到这一点,你可以使用random.sample。为了您的使用情况下,

indexes = random.sample(range(len(songs_and_artists)), 2) # 2 random songs (sampling without replacement)
# song 1
random_song, random_artist = songs_and_artists[indexes[0]]
# song 2
random_song, random_artist = songs_and_artists[indexes[1]]

另外,我建议你把你的代码的功能和与每个所选歌曲使用它。


0
投票

为了让两个以上的问题每场比赛,你必须做这样的事情:

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)]

def getSongAndArtist():
    randomIndex = random.randrange(0, len(songs_and_artists))
    return songs_and_artists.pop(randomIndex)


while(len(songs_and_artists) > 0):
    random_song, random_artist = getSongAndArtist()
    #play game with the song

您保存的歌曲列表中的一个Python列表,只要你有更多的歌曲一起玩弹出一个随机出每一轮。

对于排行榜,你要问一个用户名,你开始游戏前和保存用户名和他们的得分列表,然后挑上的人。你也应该知道如何得分用户

© www.soinside.com 2019 - 2024. All rights reserved.