如何使用代码在 Python 中停止我的程序?

How do I stop my program in Python using code?

这是我的代码。我在互联网上搜索了答案,但要么我不明白,要么对我不起作用。请帮帮我,我将不胜感激。

   sleep = input("Commander, would you like to sleep now? If yes then we can take out your bed. ")
if sleep == "yes":
    Energy = Energy + 5
    print("We have taken out your bed. The spaceship is on autopilot and you may now sleep.")
    time.sleep(4)
    print("2 weeks later...")
else:
    Energy = Energy - 5
    print("Ok. It is all your choice. BUT you WILL lose energy. Lets carry on with the journey. You have",Energy,"energy remaining.")
    time.sleep(4)
print("Commander, you have been extremely successful so far. Well done and keep it up!")
time.sleep(6)
direction = input("Oh no Sir! There is trouble ahead! Please make your decision quick. It's a matter of life and death. It is also a matter of chance! There are many asteroids ahead. You may either go forwards, backwards, left or right. Make your decision...before it's too late! ")  
if direction == "left":
    Coins = Coins + 15
    Fuel =  Fuel - 15
    while True:
        print ("You have managed to pass the asteroids, you may now carry on. You have",Fuel,"fuel left.")
        break
        continue
elif direction == "backwards":
    print("You have retreated and gone back to Earth. You will have to start your mission all over again.")
    time.sleep(2.5)
    print("The game will now restart.")
    time.sleep(2)
    print("Please wait...\n"*3)
    time.sleep(5)
    keep_playing = True
    while True:
         script()
elif direction == "forwards":
    Fails = Fails + 1
    print("You have crashed and passed away. Your bravery will always be remembered even if you did fail terribly. You have failed",Fails,"times.")
    time.sleep(3)
    ans = input("Do you want to play again? ")
    if ans == "yes":
        time.sleep(3)
        script()
    else:
        print("Our Earth is now an alien world...") 
        # Program stop here...

在最后一行我希望程序停止: 打印("Our Earth is now an alien world...")

但是,我知道有一些方法可以停止,例如 quit()exit()sys.exit()os._exit()。问题是 sys.exit() 停止了代码,但出现以下消息:

Traceback (most recent call last):
  File "C:\Users\MEERJULHASH\Documents\lazy", line 5, in <module>
    sys.exit()
SystemExit

另一方面,当我尝试在最后一行代码中使用 os._exit() 时,会出现一条错误消息,指出 TypeError: _exit() takes exactly 1 argument (0 given). exit()quit()不推荐用于生产代码。

我的问题是,是否有任何退出命令可以阻止您的代码继续运行而不显示任何消息或以 >>> 结尾,或者它只是关闭程序?提前致谢...

对于您想要做的事情,一个简单的选择是使用 while 循环。

类似的东西(您必须根据自己的需要进行调整):

keep_playing = True

while keep_playing:
    print('Some actions...')

    if input('Do you want to keep playing? ') == 'no':
        keep_playing = False
        break

您可以重复整个程序或只重复其中的一部分。 (取决于你用 while 循环包装的内容)

我在此处提供的代码非常基础,因此您需要对其进行调整。