如何让python识别从外部fi中随机选择的保存变量

2024-10-02 20:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,随机选择和打印歌曲名称和艺术家从外部文本文件。 我已经将行拆分为a,b格式,但一旦我回答了问题,程序将无法识别变量

file = open("Songz.txt", "r")

lines = file.readlines()

random_lines = random.choice(open("Songz.txt").readlines())

Song = random_lines

a,b=(Song.split(","))
print(a)
print(b)

Answer1 = input().upper()

if Answer1 == b:
        print(" Correct ")
        Quiz_Score = Quiz_Score + 3
else:
        print("incorrect")

一旦代码到达 if Answer1 == b:

第节,代码似乎忘记了变量(b)的值。知道为什么吗


Tags: 代码程序txtifsongrandomopenquiz
1条回答
网友
1楼 · 发布于 2024-10-02 20:33:53

问题似乎出在您从文件中读取的数据上。 实际上,使用readlines方法得到的列表最后会有额外的\n符号

['SONG1, ANSWER1\n', 'SONG2, ANSWER2\n', 'SONG3, ANSWER3\n']

所以您需要使用strip()来清理它们:

with open("Songz.txt", "r") as f:
    lines = f.readlines()

random_line = random.choice(lines)

a, b = random_line.split(",")
print(a)
print(b)

answer1 = input().upper()

# strip() will take care of the '\n' and the surrounding spaces if any
if answer1 == b.strip():
    print(" Correct ")
    quiz_score += 3
else:
    print("incorrect")

相关问题 更多 >