How to exit a python script in an if statement

54.0K    Asked by ClareMatthews in Python , Asked on Jul 27, 2021

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

Answered by Deepa bhawana

To stop code execution in Python you first need to import the sys object. After this, you can then call the exit() method to stop the program from running.


You can follow this: 

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("ok, sayonnara")
      exit()

edit: use input in python 3.2 instead of raw_input



Your Answer

Answer (1)

To exit a Python script within an if statement, you can use the sys.exit() function from the sys module. This function terminates the script and returns an optional status code.


Here's an example:

import sys
# Your if statement
if condition:
    print("Exiting the script")
    sys.exit() # Exiting the script here
# Code continues here if condition is not met
print("Script continues after the if statement")

Make sure to import the sys module at the beginning of your script. When sys.exit() is called, the script will terminate immediately, and any code following the call will not be executed.



7 Months

Interviews

Parent Categories