如何验证Python中的随机选择?



我一直在尝试制作一个愚蠢的小程序,向用户随机输出来自《王国之心》或《Alan Wake》(都包含在.txt文件中)的引用,但我遇到了一个障碍。我已经让程序从任意一个文本文件(驻留在列表中)中选择了一个随机引用,为了完成,我只需要验证用户输入是否与随机选择匹配。

import os
import sys
import random
with open(os.path.join(sys.path[0], "alanwake.txt"), "r", encoding='utf8') as txt1:
wake = []
for line in txt1:
wake.append(line)
with open(os.path.join(sys.path[0], "kh.txt"), "r", encoding='utf8') as txt2:
kh = []
for line in txt2:
kh.append(line)
random_kh = random.choice(kh)
random_wake = random.choice(wake)
choices = [random_kh, random_wake]
quote = random.choice(choices)
print(quote)
print("Is this quote from Kingdom Hearts or Alan Wake?")
inp = input().lower()

这是我目前得到的。我确实试过这样做:

if quote == choices[0] and inp == "kingdom hearts":
print("Correct!")
if quote == choices[1] and inp == "alan wake":
print("Correct!")
else:
print("Incorrect")

但发现它总是打印为不正确。任何帮助将不胜感激!我对编程很陌生。

如果有多个if语句这意味着程序会分别检查它们同时检查第一个if语句如果是正确的就会打印"正确"然后检查下一个if语句如果这个是假的就会打印"不正确",试试这个

if quote == choices[0] and inp == "kingdom hearts":
print("correct")
elif quote == choices[1] and inp == "alan wake":
print("correct")
else:
print("incorrect")

在这里你检查所有的选项,当其中一个是正确的,它停止比较并打印msg。

最新更新