while 循环条件不是由用户输入触发的

While loop condition not triggered by user input

我正在开发一个小游戏来锻炼我的 Python 技能。正如您在下面看到的,我一直坚持让程序在用户输入错误值后继续运行。

我尝试的其中一件事是摆脱 while 循环并将 if 语句包装在递归函数中。但是,我不确定这是否是正确的方法,目前它有点超出我的水平。欢迎任何想法!

print("Greetings, weary wanderer.")
print("Welcome to Freyjaberg. Choose your weapon.")
#user able to select from list, needs input and to check which they pick

weapon_choice = (input("You can choose between three weapons to defeat the beast!"
                   " Press 1 for Axe, 2 for Crossbow, 3 for Sword."))

while True:
    weapon_choice <= '4'
    if weapon_choice=='1':
        print("You chose the Axe of Might")
        break
    elif weapon_choice=='2':
        print("You chose the Sacred Crossbow")
        break
    elif weapon_choice=='3':
        print("You chose the Elven Sword")
        break
    else:
        weapon_choice >= '4'
        print("Wanderer, there is no such weapon. Please choose from the ones available.")
        input("You can choose between three weapons to defeat the beast! "
              "Press 1 for Axe, 2 for Crossbow, 3 for Sword.")

如果我输入 1、2 或 3,它工作正常!

Greetings, weary wanderer.
Welcome to Freyjaberg. Choose your weapon.
You can choose between three weapons to defeat the beast! Press 1 for Axe, 2 for Crossbow, 3 for Sword.2
You chose the Sacred Crossbow
Now you must enter the first dungeon. Prepare yourself!

Process finished with exit code 0

如果我输入 4 或以上,它会显示我期望的正确错误消息。到目前为止,一切都很好。然后它再次提示我(如预期的那样)。但是当我现在键入 1、2 或 3 时,它不理解并继续。它一直告诉我这是错误的。

Greetings, weary wanderer.
Welcome to Freyjaberg. Choose your weapon.
You can choose between three weapons to defeat the beast! Press 1 for Axe, 2 for Crossbow, 3 for Sword.4
Wanderer, there is no such weapon. Please choose from the ones available.
You can choose between three weapons to defeat the beast! Press 1 for Axe, 2 for Crossbow, 3 for Sword.1
Wanderer, there is no such weapon. Please choose from the ones available.
You can choose between three weapons to defeat the beast! Press 1 for Axe, 2 for Crossbow, 3 for Sword.

您必须在 while 循环中重估 weapon_of_choice 变量,如 weapon_of_choice = input("You can choose between three weapons to defeat the beast! Press 1 for Axe, 2 for Crossbow, 3 for Sword.") 中一样。 对 input 的调用仅要求用户输入,而 returns 输入值,您必须决定如何处理它。

在 while 循环中获取用户输入:

while True:
    weapon_choice = (input("You can choose between three weapons to defeat the beast!"
               " Press 1 for Axe, 2 for Crossbow, 3 for Sword."))
    try:
        weapon_choice = int(weapon_choice)
    except Exception as e:
        print ("Please enter a valid number!")
        continue
    if weapon_choice==1:
        print("You chose the Axe of Might")
        break
    elif weapon_choice==2:
        print("You chose the Sacred Crossbow")
        break
    elif weapon_choice==3:
        print("You chose the Elven Sword")
        break
    else:
        print("Wanderer, there is no such weapon. Please choose from the ones  available.")