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

时间:2015-07-19 11:16:42

标签: python exit

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

   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...

在最后一行,我希望程序停止: print(“我们的地球现在是一个外星世界......”)

但是,我知道有一些方法可以停止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()不是建议用于生产代码。

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

1 个答案:

答案 0 :(得分:2)

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

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

keep_playing = True

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

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

您可以重复整个程序或仅重复部分程序。 (取决于你以这种方式用while循环包装的内容)

我在这里给你的代码是非常基本的,所以你需要调整它。