即使用户输入了正确的单词,我在第 4 行和第 6 行中的 if 语句也会继续运行。我很困惑。有什么建议么?已经尝试让它工作一天了。
boi = input("Do you want to enter a part of a house or a word, (\"house part\" or \"word\")? ")
print(boi)
if boi != "house part":
print("I do not understand", boi +".")
elif boi != "word":
print("I do not understand", boi + ".")
if boi == "house part":
hp = input("Please enter a part of a house: ")
print(hp)
if hp == "basement":
print("calf")
elif hp == "wall":
print("skin")
elif hp == "attic":
print ("hip")
elif hp == "kitchen":
print("abdomen")
elif hp == "study":
print("wrist")
else:
print("I do not know anything about a(n)", hp + ".")
elif boi == "word":
w = input("Please enter a word: ")
print(w)
if w == "attorney":
print("macilmud")
elif w == "chicken":
print("sleent")
elif w == "consider":
print("floria")
elif w == "application":
print("sailinexemy")
elif w == "prepare":
print("capied")
else:
print("I do not know anything about a(n)", w + ".")
答案 0 :(得分:2)
所有输入要么不是一个,要么不是另一个。您需要将这两者合并为一个条件,例如:
if boi not in ("house part","word"):
print("I do not understand", boi + ".")
或者,更简单地说,在下一个条件中添加一个最后的 else:(并删除第一个)。
if boi == "house part":
...
elif boi == "word":
...
else:
print("I do not understand", boi + ".")
答案 1 :(得分:1)
您的代码:
if boi != "house part":
print("I do not understand", boi +".")
elif boi != "word":
print("I do not understand", boi + ".")
输入 house part
将导致 I do not understand house part.
,因为 house part
不等于满足 word
的 elif boi != "word":
。看起来您想将这两个语句合二为一:
if boi not in ("house part", "word"):
这是因为您当前的代码是这样运行的:
#user enters "house part"
if boi != "house part":
#boi is equal to "house part" so the if returns
#false and continues to the elif
print("I do not understand", boi +".")
elif boi != "word":
#boi is not equal to "word" so the elif is satisfied and
#the below statements are run.
print("I do not understand", boi + ".")
答案 2 :(得分:0)
当你想验证输入时,你可以使用下面的这个部分来代替:
if boi != "house part":
print("I do not understand", boi +".")
elif boi != "word":
print("I do not understand", boi + ".")
使用这个:
if boi != "house part" and boi != "word":
print("I do not understand", boi +".")