首页 > 解决方案 > Python if-else 语句的问题

问题描述

我正在为 IT 课做作业。非常基础的 Python 项目。我没有这方面的经验,但能够掌握大部分时间发生的事情。该项目涉及做出涉及随机整数选择的选择。我可以在 if-else 格式中获得按我想要的方式工作的选项,但是 else 命令没有按照我想要的方式响应。选项都正确加载,但如果由于某种原因选择是 1-3,则程序会在打印“if”语句后打印“else”语句。如果他们选择选项 4 或选择无效数字(else 语句的原因),则不会发生这种情况。

我在程序的上一部分中没有这个问题。我一定错过了什么,但我不知道是什么。我应该重申我在这方面非常初学者,基本上是按照作业的指示复制粘贴代码,然后根据我的需要对其进行编辑。

interactions = ["Back Away Slowly","Point Towards the Chamber","Attack","Try To Communicate",]
import random
badchoice = random.randint(1,3)
loop = 1

while loop == 1:
    choice=menu(interactions, "How do you decide to interact?")
    print("")

    if choice == 1:
        print("You start to slowly back away from the man.")
        print("You worry you are giving off the wrong attitude.")
        print("")

        if choice == badchoice:
            loop=0
            print("The stranger was already weary of your presence.")
            print(interactions[choice-1], "was not the correct decision.")
            print("He calls for help. Villagers and guards immediately surround you.")
            print("You are thrown back into the chamber. Hitting your head, and getting knocked unconscious in the process.")
            print("You are back where you started and the items have been removed.")
            print("There is no escape.")
            print("Lamashtu's Curse can not be broken.")
            print("Game Over.")

        else:
            print("The stranger looks at you in confusion.")
            print("")

# Choices 2 and 3 go here. Same code. Seemed redundant to post all of it.    


    if choice == 4:
        loop=0
        print("The stranger is weary of your presence, and can not understand you.")
        print("You can see in his eyes that he wants to help,")
        print("and he escorts you back to his home for the time being.")
        print("He offers you some much needed food and water.")
        print("You are no closer to understanding what curse brought you here.")
        print("Perhaps tomorrow you will have more time to inspect your surroundings.")
        print("In time you may be able to communicate enough  with your host to explain your dilemma,")
        print("but for now you are trapped 6000 years in the past with no other options.")
        print("At least you've made it out alive thus far......")
        print("To be continued...")

    else:
        print("Please choose a number between 1 and 4.")

标签: pythonloopsif-statement

解决方案


你的逻辑不正确。您的最终if声明将选择4指向它的True分支,并将其他所有内容指向False分支。Python 完全按照您的指示去做。没有对先前块的逻辑引用。

你需要的逻辑是

if choice == 1:
    ...
elif choice == 2:
    ...
elif choice == 3:
    ...
elif choice == 4:
    ...
else:
    print("Please choose a number between 1 and 4.")

推荐阅读