[英]How do I loop multiple conditions in different statements, and make it loop If the conditions are not met?
我需要專門針對我的代碼的幫助。 output 似乎不是我想要的。 如果我嘗試 while 循環它,並且值是錯誤的,它仍然會繼續。 這里有很多錯誤,我不知道如何修復。
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)
評估為 boolean,它看到一個str
因此評估為True
並且while
循環繼續運行。
您還應該使打印語句中的選項在文本上與選項相同,否則用戶將鍵入“Axe”,它與“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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.