如何让Python 3将外部文件中的随机单词注册为变量



我是一名中学计算机科学专业的学生,目前正在与NEA的某个方面作斗争,我们可以获得代码方面的帮助。NEA的目的是创建一个游戏,可以从外部文件中随机选择歌曲和艺术家,然后让用户猜测这是哪首歌。我遇到的问题是,当我运行程序时,代码的random方面(从外部文件选择的歌曲名称和艺术家(似乎没有被if语句注册。我想不出更好的方法来解释我的问题,但如果你运行代码,我相信你会看到我的问题。我去掉了大部分不属于问题的多余代码,使其更容易理解,因为正如我之前所说,我在这方面还是个新手。我环顾四周,似乎找不到答案。任何形式的帮助都将不胜感激。

username = 'Player1'
password = 'Password'
userInput = input("What is your username? (Case Sensitive)n")
if userInput == username:
userInput = input("What Is Your Password? (Case Sensitive)n")
if userInput == password:
print(
"Welcome! In this game you need to guess each songs name after being given its first letter and its artist. Good luck!"
)
else:
print("That is the wrong password. Goodbye ;)")
exit()
else:
print("That is the wrong username. Goodbye ;)")
exit()
startgame = 'Start' 'start'
userInput1 = input("Click Any Button And Click Enter To Begin Game:")
if userInput1 == startgame: 'Start'
print("Welcome To The Game")
import random
Song = [line.strip() for line in open("Songnames.txt")] #Currently in the external file I have removed all of the other songs apart from H______ By Ed Sherran.
print(random.choice(Song))
userguess = input("Whats Your Answer?n")

if userguess == ("Happier") and (random.choice(Song)) == "H______ By Ed Sherran": #The program will continue to return 'Incorrect'.
print("Nice One")
else:
print ("Incorrect")

任何形式的帮助都将不胜感激,我已经在这个网站和其他网站上寻找了一段时间的答案,但如果我似乎错过了一个明显的答案,我深表歉意。

当我运行代码时,它似乎可以工作。(My Songnames.txt包含一行H______ By Ed Sherran。(

您的Songnames.txt是否可能至少包含一个空行?如果是这样,过滤空行可能会解决问题:

Song = [line.strip() for line in open("Songnames.txt") if line.strip()]

为您的代码提供其他一些建议:

startgame = 'Start' 'start'
userInput1 = input("Click Any Button And Click Enter To Begin Game:")
if userInput1 == startgame: 'Start'
print("Welcome To The Game")

这没有道理。除了关于按钮和点击的误导性提示外,if userInput1 == startgame: 'Start'什么都不做,甚至连打印开始都不做。无论用户输入什么,游戏都会开始。

实际游戏也有一些问题,最重要的是,当你有多首歌曲时,你会随机选择一首歌曲两次。给定足够多的歌曲,这些歌曲几乎总是两首不同的歌曲,因此print将完全具有误导性。最好选择一首歌曲,并将其分配给一个变量:

import random
songs = [line.strip() for line in open("Songnames.txt") if line.strip()]
computer_choice = random.choice(songs)
print(computer_choice)
userguess = input("Whats Your Answer?n")
if userguess.lower() == computer_choice.lower():
print("Nice One")
else:
print("Incorrect")

我通过比较用户猜测和计算机选择的小写版本,自由地使比较不区分大小写。

最新更新