【发布时间】: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