【问题标题】:Function not Running inside an "if" statement Python 3函数未在“if”语句 Python 3 中运行
【发布时间】:2016-11-06 03:01:10
【问题描述】:

我正在尝试用 Python 编写一个密室逃脱游戏。
当我使用 pycharm 运行代码时,进程以“进程以退出代码 0 结束”结束。

函数的定义有问题吗?
这是我的代码(有点长):

choice = None

def main_choice():

    print("1. Examine door")

    print("2. Examine painting")

    print("3. Examine desk")

    print("4. Examine bookshelf")

    choice == input("Make your choice: ")


def door():

    print("1. Try to open door")

    print("2. Take a closer look")

    print("3. Go back to where you were.")

    door_choice = input("What now? ")

    if door_choice == "1":

        print("The door is too heavy to open with your bare hands.")

        door()

    if door_choice == "2":

        print("There is a red light above the door, but it seems to have no purpose.")

        print("You notice a 9 key keypad next to the door. It looks like it will accept a 3 digit code.")

        keypad_code = input("Would you like to enter a code?").lower

        if keypad_code == " yes":

             guess = input("ENTER CODE: ")

             if guess == complete_key:

             print("The light turns green and you hear the sound of a mechanical lock unlocking. The door opens.")

             print("YOU WIN!!!")

        if guess != complete_key:

             print("Wrong code.")

             main_choice()

    if door_choice == "3":

        main_choice()

    else:

        print("You didn't answer")


main_choice()

if choice == "1":

    print("You walk to the door")

    door()

我认为这可能是最后一个“if”语句,但我并不肯定。

【问题讨论】:

  • 基本上你想在不退出的情况下继续运行程序吗?
  • 一种快速的调试方法是在调用 main_choice() 后进行调试打印,以确保您首先已将 choice 分配给某个对象。

标签: python python-3.x


【解决方案1】:

您需要在 main_choice 函数中将 choice == input("Make your choice: ") 更改为 choice = input("Make your choice: ")

def main_choice():

    print("1. Examine door")

    print("2. Examine painting")

    print("3. Examine desk")

    print("4. Examine bookshelf")

    choice = input("Make your choice: ")

否则,choice 变量仍将是 None,而 if choice == "1": 将始终为 False。

【讨论】:

    【解决方案2】:

    你应该写:

    choice = input("Make you choice: ")
    

    而不是:

    choice == input("Make you choice: ")
    

    双等号返回布尔值而不是更改值。

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多