Python if-else语句存在问题

时间:2019-07-01 18:06:04

标签: python loops if-statement

我正在为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.")

2 个答案:

答案 0 :(得分:0)

您的逻辑不正确。您最后的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.")

答案 1 :(得分:0)

else仅适用于同一级别的最新if,即一个用于数字4。其他三个if语句都是独立的。因此,在检查完每个选项之后,它会检查选项是否为4,如果不是,则运行else。

您需要使所有这些都成为同一语句的一部分,对于第一个语句之后的每个if,请使用elif。像这样:

if choice == 1:
    ...
elif choice == 2:
    ...
elif choice == 3:
    ...
elif choice == 4:
    ...
else:
    ...