因此,我正忙于制作一个基于文本的交互式游戏,用户可以用自己的单词输入答案。
我写了一段代码来在用户输入某些单词时打印某些字符串,但我无法使其正常工作。
无论我输入什么,它总是打印“ NOVA ENTER THE SPACECRAFT” 我在做什么错了?
下面是我的代码段:
craft_cave = input(char_name + ": I should probably search the ship for supplies and explore this cave, which should I do first? ")
print("")
if "craft" or "Craft" or "ship" or "Ship" in craft_cave:
print("NOVA ENTERS THE SPACECRAFT")
elif "cave" or "Cave" or "mountain" or "Mountain" in craft_cave:
print("NOVA LOOKS AROUND THE CAVE")
else:
print("Invalid answer")
答案 0 :(得分:2)
您需要逐字检查单词。尝试类似的东西:
vehicle_words = ["craft", "Craft", "ship", "Ship"]
cave_words = ["cave", "Cave", "mountain", "Mountain"]
if any(w in craft_cave for w in vehicle_words):
print("NOVA ENTERS THE SPACESHIP")
elif any(w in craft_cave for w in cave_words)
print("NOVA LOOKS AROUND THE CAVE")
else:
print("Invalid Answer")
答案 1 :(得分:1)
条件错误,它将检查"craft"
的值是否正确。您应该执行以下操作:
if "craft" in craft_cave or "Craft" in craft_cave or "ship" in craft_cave or "Ship" in craft_cave:
# continue
更好:
if any(map(lambda word: word in craft_cave, ("craft", "Craft", "ship", "Ship"))):
# continue
答案 2 :(得分:0)
if "craft" or "Craft" or "ship" or "Ship" in craft_cave:
被评估为
if ("craft" or ("Craft" or ("ship" or ("Ship" in craft_cave) ) ) ):
"craft"
首先被评估为布尔值,从而得到True
,
所以我们有
if (True or ("Craft" or ("ship" or ("Ship" in craft_cave) ) ) ):
并且由于True or x
始终为True
,因此该语句的计算结果为
if True:
因此第一个if条件始终求值为True
。
您需要直接检查每个if条件中的每个单词
spacecraft_keywords = ["craft", "Craft", "ship", "Ship"]
cave_keywords = ["cave", "Cave", "mountain", "Mountain"]
def contains_any(keywords, s):
return any(keyword in s for keyword in keywords)
if contains_any(spacecraft_keywords, craft_cave):
pass
elif contains_any(cave_keywords, craft_cave):
...
答案 3 :(得分:0)
一种简单的方法,将所有单词都放在列表中
craft_cave = input( ": I should probably search the ship for supplies and explore
this cave, which should I do first? ")
print("")
list1 = ('craft', 'Craft', 'ship', 'Ship')
list2 = ('cave', 'Cave', 'mountain', 'Mountain')
if any(word in craft_cave for word in list1):
print("NOVA ENTERS THE SPACECRAFT")
elif any(word in craft_cave for word in list2):
print("NOVA LOOKS AROUND THE CAVE")
else:
print("invalid")