为什么我的if语句运行不正确?



即使用户输入正确的单词,第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 + ".")

所有输入要么不是其中一个,要么不是另一个。您需要将这两个组合成一个条件,例如:

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 + ".")

代码:

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不等于满足elif boi != "word":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 + ".")

当您需要验证输入时,您可以使用下面的instead of部分:

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 +".")

最新更新