如何在不同的语句中循环多个条件,并在条件不满足的情况下使其循环



我的代码需要特别的帮助。它似乎没有输出我想要的东西。如果我试图在循环它的同时,但值是错误的,它仍然会继续。这里有很多错误,我不知道如何修复。

weapon_2 = "axe"
weapon_3 = "spiked club"
weapon_1 = weapon_1.strip().lower()
weapon_2 = weapon_1.strip().lower()
weapon_3 = weapon_1.strip().lower()
weapon = input ("Please select a weapon: Sword, Axe, Spiked Club.n")
weapon = weapon.strip().lower()

if weapon == weapon_1:
print("Nice choice! I would pick {} too!".format(weapon))

elif weapon == weapon_2:
print("Nice choice! I would pick {} too!".format(weapon))

elif weapon == weapon_3:
print("Nice choice! I would pick {} too!".format(weapon))
while weapon != (weapon_1) or (weapon_2) or (weapon_3):
print("Invalid option.")
weapon = input ("Please select a weapon: Sword, Axe, Spiked Club.n")    

替换:

while weapon != (weapon_1) or (weapon_2) or (weapon_3):

带有:

while weapon not in (weapon_1, weapon_2, weapon_3):

or(weapon_2)计算为布尔值,它看到str,因此计算为True,并且while循环继续运行。

您还应该使打印语句中的选项在文本上与选项相同,否则用户将键入";Axe";,其不匹配";斧头;然后被告知这是一个无效的选项。

需要对while循环进行一些细化,以保持"循环";

weapon_1, weapon_2, weapon_3  = "sword", "axe", "spiked club"
while True:
weapon = input("Please select a weapon: Sword, Axe, Spiked Club.n").strip().lower()

if weapon == weapon_1:
print(f"Nice choice! I would pick {weapon_1} too!")
elif weapon == weapon_2:
print(f"Nice choice! I would pick {weapon_2} too!")
elif weapon == weapon_3:
print(f"Nice choice! I would pick {weapon_3} too!")
elif weapon == 'stop':
break
else:
print("Invalid Input")
weapons = ["sword", "axe", "spiked club"]
while True:
# input
user_input = input("Please select a weapon: Sword, Axe, Spiked Club. ('stop' to exit)n")
user_input_lower = user_input.strip().lower()
if user_input_lower == 'stop':
break
# weapon precessing
weapon = user_input_lower
if weapon in weapons:
print(f"Nice choice! I would pick {user_input} too!")
else:
print("Invalid Input")

最新更新