how to exit a python script in an if statement

0 votes
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.
Sep 19, 2018 in Python by Priyaj
• 57,700 points

1 answer to this question.

0 votes

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

edit: use input in python 3.2 instead of raw_input

answered Sep 19, 2018 by bug_seeker
• 15,510 points
How do I condition my program to exit?

It usually closes the terminal window by itself after the program.
Hi @Ceefon, did you try the above mentioned code? It worked fine for me.
Using Python 3.7.6, I get 'NameError: name 'exit' is not defined'

Hi, @Nick,

Could you please post your code snippet here, what exactly are you trying to do? It will be helpful for us to resolve it ASAP.

import sys

# to exit the code


Hi, @MDG,

Importing sys will not be enough to make exit live in the global scope.

You either need to do

from sys import exit
This worked like dream for what I needed !!!!!!! Thank you!!

Related Questions In Python

+1 vote
1 answer

How to check if a string is null in python

Try this: if cookie and not cookie.isspace(): # the ...READ MORE

answered Aug 20, 2018 in Python by Priyaj
• 57,700 points
0 votes
1 answer

How to break for loop in an if statement

You can break out of each loop ...READ MORE

answered Nov 16, 2018 in Python by Jino
• 5,770 points
0 votes
1 answer

How to use nested if else statement in python?

The working of nested if-else is similar ...READ MORE

answered Nov 19, 2018 in Python by Nabarupa
+1 vote
1 answer

How to Profile a script in Python

Python includes a profiler called cProfile. It ...READ MORE

answered Nov 21, 2018 in Python by SDeb
• 13,250 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,456 views
0 votes
0 answers
+2 votes
2 answers

How can I replace values with 'none' in a dataframe using pandas

Actually in later versions of pandas this ...READ MORE

answered Aug 13, 2018 in Python by bug_seeker
• 15,510 points
0 votes
1 answer

When to use %r instead of %s in Python? [duplicate]

The %s specifier converts the object using ...READ MORE

answered Aug 2, 2018 in Python by bug_seeker
• 15,510 points