不一致的Python结果

2024-10-03 09:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我遇到了这样一个问题,我的代码在随机时间不一致地失败,这个问题以前已经得到了回答:(Python 3.7.3 Inconsistent code for song guessing code, stops working at random times现在我不得不为我正在做的猜歌游戏添加一个排行榜。我随机选择其中一些是用来寻找艺术家和歌曲。如果正确,它将删除歌曲和艺术家,以防止重复和进行。代码如下:

loop = 10
attempts = 0
ArtCount = len(artist)
for x in range (ArtCount):
    print(ArtCount)
    randNum = int(random.randint(0, ArtCount - 1))
    randArt = artist[randNum]
    ArtInd = artist.index(randArt)# catches element position       
    songSel = songs[randNum]
    print (randNum)
    print ("The artist is " + randArt)
    time.sleep(0.5)
    songie = songSel
    print( "The songs first letter be " + songSel[0])
    time.sleep(0.5)
    print("")
    question = input("What song do you believe it to be? ")
    if question == (songSel):
        songs.remove(songSel)

        artist.remove(randArt)
        print ("Correct")
        print ("Next Question")
        if attempts ==0:
            points = points + 5
            print("+5 Points")
            print("")
     if question != (songSel):
        loop = loop + 1
        attempts = attempts + 1

        print("")
        print("Wrong,", attempts, "questions wrong, careful!")
        print("")
        time.sleep(0.5)

    if attempts == 5:
        break
        print("GAME OVER")

请原谅我的乱七八糟,我刚开始做大代码,完成后会清理干净的。我有一个额外的问题,让计数控制循环为10(问题的数量),然后当你得到一个错误的问题时,必须去循环,我试着让它循环列表中歌曲的数量,我也试着做一个变量,当你得到错误时,加1,这样你就有空间回答,但这也不起作用。在实现了排行榜之后,它现在不会删除任何歌曲(我每次都在用缩进来打印排行榜)

randArt = artist[randNum]
IndexError: list index out of range

我不知道为什么这是代码的问题,我甚至不知道这是必要的。你知道吗


Tags: 代码loopiftimeartistsleep歌曲print
2条回答

请不要用

randNum = int(random.randint(0, ArtCount - 1))

您可以使用以下方法轻松获得随机艺术家:

randArt = random.choice(artist)

问题是你的代码修改艺术家数组长度时,你删除项目的真实答案。你需要得到正确的艺术家计数后,你改变。你知道吗

for x in range (ArtCount):
    print(ArtCount)
    count = len(artist)  # get the new length here
    randNum = int(random.randint(0, count - 1))  # use the new length here instead of your old ArtCount

相关问题 更多 >