如何在if语句中退出python脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17179615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:41:24  来源:igfitidea点击:

how to exit a python script in an if statement

pythonpython-3.x

提问by ethan

I'm using Python 3.2 and trying to exit it after the user inputs that they don't want to continue, is there code that will exit it in an if statement inside a while loop? I've already tried using exit(), sys.exit(), sys.quit(), quit(), and raise SystemExit.

我正在使用 Python 3.2 并尝试在用户输入他们不想继续后退出它,是否有代码将在 while 循环内的 if 语句中退出它?我已经使用已经尝试过exit()sys.exit()sys.quit()quit(),和提高SystemExit

回答by d512

This works fine for me:

这对我来说很好用:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use inputin python 3.2 instead of raw_input

编辑:input在 python 3.2 中使用而不是raw_input