为什么我的验证码标记输入错误,即使正确?

我正在尝试编写一个游戏,该游戏显示歌曲的首字母和艺术家,并要求用户分两次尝试猜测歌曲。但是,当我尝试验证答案是否正确(总是如此)时,它仍然说它是错误的。


我的代码如下:


import random


for x in range(0, 13):

    randNum = int(random.randint(0, 13))


    song = open("Songs.txt", "r")

    songname = str(song.readlines()[randNum])

    print(songname[0])

    song.close()


    artist = open("Artists.txt", "r")

    artistname = artist.readlines()[randNum]

    print(artistname)

    artist.close()


    songGuess = input("What is the song called?")

    for x in range(0,1):

        if songGuess == songname:

            print("Answer correct!")

        else:

            songguess = input("Incorrect! Try again:")

            x = x + 1

        if x == 2:

            print("GAME OVER")

            break


    x = x+1

    if x == 13:

        break 

quiz()

应该发生的是,当只给出歌曲名称和艺术家的第一个字母时,用户应该有两次尝试猜测歌曲的名称,如果他们在游戏结束时无法猜到,它应该结束。


繁花如伊
浏览 119回答 2
2回答

慕桂英3389331

您正在尝试使用 X 作为总回合数以及一回合内猜测尝试次数的计数器。为匝数创建一个单独的变量(例如我的示例中的 num_turns)。您正在修改循环中的变量 x。我还没有看到很多案例表明这是一个好主意。for 循环应该为你做所有的递增。正如其他人所说, while 循环在这里可能更有意义,因为您正在检查正确答案,直到找到一个或达到最大猜测您不需要检查 for 循环的结尾并跳出它。这并不是真正相关,但您正在阅读每次迭代的文件。将它们一次加载到内存中并从那里访问它们会更有效。我会按如下方式重写代码,但有许多不同的变体可以工作。import random# Set these to whatever makes sense for your use case.max_turns = 5max_guesses = 2# Load these from wherever you want. This is just some dumb testing data.songs = load_songs() # you'll need to write some code to do thisartists = load_artists() # you'll need to write some code to do thisfor turn_counter in range(max_turns):    # Pick a random song:    randNum = int(random.randint(0, 11))    song_name = songs[randNum]    artistname = artists[randNum]    print()    print(song_name[0])    print(artistname)    # Prompt for a guess:    song_guess = input("What is the song called?\n> ")    # Let the user guess until they hit the max tries:    guess_counter = 0    correct_guess = False    while True:        if song_guess == song_name:            correct_guess = True            break        guess_counter += 1        if guess_counter>=max_guesses:            break        # Song wasn't guessed correctly and we haven't hit         # the max guesses yet, so try again:        song_guess = input("Incorrect! Try again:\n> ")    # We're out of the while loop, so either the song was guessed    # correctly, or we hit the max number of guesses. Find out which:    if correct_guess:        print("Answer correct!")    else:        print("GAME OVER")        break
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python