【问题标题】:How do you check a randomly generated value from an array against user input in python?如何根据 python 中的用户输入检查从数组中随机生成的值?
【发布时间】:2018-12-26 03:02:34
【问题描述】:

我正在为我的 OCR GCSE 编程项目做一个音乐测验。 python 程序的目的是从数组中随机生成一首歌曲,显示歌曲的首字母并显示艺术家,然后让用户猜测歌曲的名称。歌曲数组和艺术家数组存储在单独的外部记事本文件中,并正确加载,显示歌曲和艺术家的首字母。我的问题是,即使用户猜对了歌曲名称,程序也会显示它不正确,并且与用户输入的正确歌曲名称不匹配。

我已尝试显示歌曲名称以确保我猜对了歌曲名称,并且还尝试复制歌曲名称并将其复制到用户输入中

import random
songlistfilecontents = open("songlist.txt", "r")
songlist = songlistfilecontents.readlines()
artistlistfilecontents = open("artistlist.txt", "r")
artistlist = artistlistfilecontents.readlines()
randomnumber = random.randint(0,11)
randomsong = songlist[randomnumber]
randomartist = artistlist [randomnumber]
initialsofsong = "".join(item[0].upper() for item in randomsong.split())

counter = 0
print("The songs' initials are " ,initialsofsong, " and the name of the 
artist is " ,randomartist)
print (randomsong)
songnameguess = input("Guess the name of the song!")
counter = counter + 1
while songnameguess != randomsong:
    songnameguess = input("Nope! Try again!")
    counter = counter + 1
if counter >=3 and songnameguess != randomsong:
    print ("Sorry, you've had two chances. Come back soon!")
elif songnameguess == randomsong:
    print ("Well done!")

我希望程序显示“干得好!”如果用户猜错歌曲不超过 3 次并且猜对了答案。但是,该程序从不显示此内容,而是显示 Nope!再试一次,并提示输入 songnameguess,直到用户猜测(不正确或正确)三次,然后打印对不起,你有两次机会。快回来吧!

【问题讨论】:

  • “不合格”行与 Stack Overflow 的工作方式完全无关。但无论如何,if counter >=3 and songnameguess != randomsong: 不在while 循环内,所以他们可以在发现错误之前进行 100 次猜测。
  • 我已经尝试了您的建议,但它并没有为我提到的问题提供解决方案。用户提供的猜测仍然总是不正确的。
  • readlines() 返回的行末尾有换行符。

标签: python


【解决方案1】:

就像@Barmar 在阅读文本文件时在 cmets 中所说的那样,您必须考虑到您将在每行末尾获取换行符这一事实。但是您的代码中还有另一个错误:在您的while 循环中,您永远不会检查用户给出的答案是否比您想要授予他的更多。因此,用户将陷入该循环,直到他给出正确的答案。

因此,只要稍加修改,它就会如下所示:

解决方案 1

import random
songlistfilecontents = open("songlist.txt", "r")
songlist = songlistfilecontents.readlines()
artistlistfilecontents = open("artistlist.txt", "r")
artistlist = artistlistfilecontents.readlines()
randomnumber = random.randint(0,11)
randomsong = songlist[randomnumber]
randomsong = randomsong.rstrip("\n")
randomartist = artistlist [randomnumber]
initialsofsong = "".join(item[0].upper() for item in randomsong.split())

counter = 0
print("The songs' initials are " ,initialsofsong, " and the name of the artist is " ,randomartist)
print (randomsong)
songnameguess = input("Guess the name of the song!")
counter = counter + 1
while counter < 3 and songnameguess != randomsong :
    songnameguess = input("Nope! Try again!")
    counter = counter + 1

if counter >=3 and songnameguess != randomsong:
    print ("Sorry, you've had two chances. Come back soon!")
elif songnameguess == randomsong:
    print ("Well done!")

【讨论】:

    【解决方案2】:

    但我们可以走得更远。

    解决方案 2

    import random
    
    with open("songlist.txt", "r") as songlistfilecontents:
        songlist = songlistfilecontents.readlines()
    
    with open("artistlist.txt", "r") as artistlistfilecontents:
        artistlist = artistlistfilecontents.readlines()
    
    randomnumber = random.randint(0,11)
    randomsong = songlist[randomnumber]
    randomsong = randomsong.rstrip("\n")
    randomartist = artistlist [randomnumber]
    initialsofsong = "".join(item[0].upper() for item in randomsong.split())
    
    
    print("The songs' initials are", initialsofsong, "and the name of the artist is", randomartist)
    print (randomsong)
    # First try
    songnameguess = input("Guess the name of the song! ")
    nb_tries_left = 2
    answer_not_found = (songnameguess != randomsong)
    while nb_tries_left > 0 and answer_not_found:
        songnameguess = input("Nope! Try again! ")
        nb_tries_left -= 1
        answer_not_found = (songnameguess != randomsong)
    
    if answer_not_found:
        print ("Sorry, you've had two chances. Come back soon!")
    else:
        print ("Well done!")
    
    • 我使用context managers打开和读取文件
    • 我使用nb_tries_left 记录停止前剩余的尝试次数。我没有计数到一个值,而是先设置该值然后递减为零。

    【讨论】:

      【解决方案3】:

      我们可以走得更远:

      解决方案3

      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)
      print(random_song)
      
      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
      
          finished = (answer_found or nb_tries_left <= 0) 
      
      if answer_found:
          print ("Well done!")
      else:
          print ("Sorry, you've had two chances. Come back soon!")
      
      • 我使用文件对象是可迭代的这一事实。所以使用zip(),我创建了一个包含歌曲和艺术家组合的元组列表。
      • 我使用random.choice() 随机选择歌曲和艺术家

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-17
        • 2021-09-26
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 2018-01-27
        • 2016-05-13
        • 1970-01-01
        相关资源
        最近更新 更多