首页 > 解决方案 > 如何让 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")

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

标签: python-3.x

解决方案


当我运行代码时,它似乎工作。(我的 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")

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


推荐阅读