我想在!=中使用多个单词,但我一生无法理解或用谷歌搜索。 任何人都可以帮忙,并解释为什么我不能做到这样: !=“否”!=“否”!=“ n”!=“ N”:等等等等
answers = ["Yes", "Not now not ever.", "Unclear answer, try again.", "Maybe.", "Probably not.", "Try again later.",
"My sources says no.", "My sources says yes.", "Only when there is a full moon.", "It is certain.",
"Cannot predict now.", "Outlook not so good", "Very doubtful.", "You may rely on it.",
"Yes - definitely.", "As I see it, yes.", "Signs point to yes."]
while str(input("Do you want to ask the Magic 8Ball a question? Yes or No? ")) != "No" != "no": # <-- problematic line
str(input("Ask the mighty 8Ball your question: "))
randomanswer = answers[random.randint(0, len(answers) -1)]
print("\n","The Magic 8Ball says: ")
print(randomanswer, "\n")
else:
return
答案 0 :(得分:5)
您可以使用元组值,例如
while foo not in ('No', 'no', 'N', 'n'):
# code
或
while foo.lower() not in ('no', 'n'):
# code
如果有大量的前哨,set
的执行速度将比元组快(对于少量值,散列是不值得的)。
您可能还想研究re
模块,以进行更复杂的模式匹配。
答案 1 :(得分:1)
尝试
while str(input("Do you want to ask the Magic 8Ball a question? Yes or No? ")) not in ["No", "no"]
答案 2 :(得分:0)
您正在寻找一种将条件语句链接在一起的方法。不幸的是,您无法以尝试的方式进行操作。但是,您可以使用and
和or
将它们链接在一起,这通常是这样做的。例如:
userinput = str(input("Do you want to ask the Magic 8Ball a question? Yes or No? "))
while userinput != "No" and userinput != "no":
# have to get user input again at end of loop
但是更好的方法是找到如何在逻辑上将其转换为单个条件,在这种情况下,请在用户输入上使用lower
:
userinput = str(input("Do you want to ask the Magic 8Ball a question? Yes or No? "))
userinput = userinput.lower() # make it lowercase
while userinput != "no":
# have to get user input again at end of loop
最后,您可以使用random.choice
从答案数组中提供随机元素。
答案 3 :(得分:0)
将有问题的行更改为:
while input("Do you want to ask the Magic 8Ball a question? Yes or No? ").strip().lower() != "no":
通过这种方式,您可以将输入字符串转换为小写(lower()
),同时还删除了用户可能在其中键入的任何空格(strip()
)
然后,如果用户键入:“否”,lower()
会将其转换为所有小写字母“否”,然后将其检查到您的!= 'no'
。
在input()
中键入的任何内容都是字符串,因此可以省略str()
。