[英]How can I make a variable equal more then one string - Python
I am working on a quiz game and when I get asked any question, i type in the right answer, which I defined in the a variable that holds that correct answer but it says it is wrong if it isn't the first word for that variable (In this case, Metallica). 我正在开展一个问答游戏,当我被问到任何问题时,我输入了正确的答案,我在一个保存了正确答案的变量中定义但它说如果它不是第一个单词就错了变量(在这种情况下,Metallica)。 Here is what my code looks like.
这是我的代码的样子。
q1answer = "Metallica" or "metallica" or "Slayer" or "slayer" or "Anthrax" or "anthrax" or "Megadeth" or "megadeth"
answerinput = str(input("name one of the 'Big Four' metal bands'"))
if answerinput == q1answer:
print ("You got the right answer!")
else:
print ("That is the wrong answer...")
Now, if I was to type in 'Metallica' it would be correct because it is the first word for the q1answer variable. 现在,如果我输入'Metallica',那将是正确的,因为它是q1answer变量的第一个单词。 But, if I type metallica, Slayer, slayer, Anthrax, anthrax, megadeth or Megadeth, I would get the wrong answer text.
但是,如果我输入metallica,Slayer,slayer,Anthrax,anthrax,megadeth或Megadeth,我会得到错误的答案文本。 Is there a way for all of these strings to be working for this one variable if i was to type anything but the first word in that variable?
如果我要键入除该变量中的第一个单词之外的任何内容,是否有一种方法可以让所有这些字符串都适用于这个变量? I'm a rookie in python so any help would be great.
我是python中的新手,所以任何帮助都会很棒。
Put them in a set and test for a correct answer using in
instead: 将它们放入一组并使用
in
来测试正确的答案:
q1answer = {"Metallica", "metallica", "Slayer", "slayer", "Anthrax", "anthrax", "Megadeth", "megadeth"}
...
if answerinput in q1answer:
Right now, your series of or
s is just resulting in the first one - "Metallica"
. 现在,你的系列
or
s只是导致第一个 - "Metallica"
。 You can also stop duplicating every name for case-insensitivity and instead use lower
: 您也可以停止复制每个名称以防止不区分大小写,而是使用
lower
:
if answerinput.lower() in q1answer:
Change your code like this: 像这样更改你的代码:
q1answer = ("metallica", "slayer", "anthrax", "megadeth")
...
if answerinput.lower() in q1answer:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.