为了账号安全,请及时绑定邮箱和手机立即绑定

到达特定行后如何停止程序?

到达特定行后如何停止程序?

绝地无双 2023-06-20 10:38:25
我正在尝试用 python 创建一个游戏,一个名为“谁想成为百万富翁?”的多项选择游戏。问题是一旦用户未能回答第一个问题,我希望程序停止执行第二个问题。print("What is the tallest being in existence?")input(("If you want to see the choices just press enter. " + name))print("Is it A, Dinosaur?")print("B, The one and only, Giraffe")print("C,The soul of the ocean Whale")print("or D, None")print("So what do you believe is the answer ? " + name + " ")answer_1 = input()if answer_1 == Q1_answer:    print("Correct! You Have Earned 100,000$ ")    score = +100000if answer_1 != Q1_answer:    print("Im sorry, You have lost the game.")print("Which famous inventor was born in 1856?")print("A Einstein")print("B, Tesla")print("C, Napoleon")print("D, Newton")answer_2 = input()if answer_2 == Q2_answer.lower():    print("Correct! It is Tesla Indeed, Your reached  200,000$ ")    score = +100000else:    print("Sorry, wrong answer. You have lost and earned 0$. ")
查看完整描述

3 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

我认为你可以用更好的方式编写你的程序,目前你不能轻易地添加问题,因为你必须为每个新问题重复整个代码。您可以将所有问题存储在一个列表中,然后遍历它们。sys.exit()由于我组织代码的方式,我也不需要。这是代码:


questions = [

    {

        "question": "What is the tallest being in existence?",

        "options": [

            "Is it A, Dinosaur?",

            "B, The one and only, Giraffe",

            "C,The soul of the ocean Whale",

            "or D, None"

        ],

        "correctOption": "a",

        "prize": 100_000

    },

    {

        "question": "Which famous inventor was born in 1856?",

        "options": [

            "A Einstein",

            "B, Tesla",

            "C, Napoleon",

            "D, Newton"

        ],

        "correctOption": "b",

        "prize": 100_000

    }

]


isGameWon = True

score = 0


for question in questions:

    print(question['question'])

    input("If you want to see the choices just press enter.")

    for option in question['options']:

        print(option)

    print("So what do you believe is the answer?")

    answer = input()

    if answer.lower() == question['correctOption']:

        score = score + question['prize']

        print("Correct! You Have Earned $" + str(score) + ".")

    else:

        isGameWon = False

        break


if (isGameWon):

    print("Congrats! You have won the game. You earned $" + str(score) + ".")

else:

    print("Sorry, wrong answer. You have lost and earned $0.")


查看完整回答
反对 回复 2023-06-20
?
MM们

TA贡献1886条经验 获得超2个赞

如果你想完全退出程序你需要调用exit方法。


import sys

...    

if answer_1 != Q1_answer:

    print("Im sorry, You have lost the game.")

    sys.exit()


查看完整回答
反对 回复 2023-06-20
?
白板的微信

TA贡献1883条经验 获得超3个赞

您可以使用 exit() 退出程序。我会打印一条消息,告诉用户程序将退出。



查看完整回答
反对 回复 2023-06-20
  • 3 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信