How to exit a python program

           A start and end are common in any process. As we know earlier to start the python script. In general, we end a python program after displaying an output.

To exit a python program, there are three methods. Here, are the three methods….

  1. 1.    Using exit() method.
  2. 2.    Using quit method.
  3. 3.    Using sys.exit() method.

Each one is coded with an example below.

1.Using exit() method:

It has the following steps.

  • ·      First open a command prompt in your system.
  • ·      It shows the below screen.
  • ·      Type “py” to enter into python environment.
  • ·      Write your print statement.

print(“Hi, welcome to python”)

·      It displays the message “ Hi, welcome to python” on the screen.

·      To exit the python program, just type exit() and press the ‘enter’ key.

·      It exits the environment.

Note: If you want to print a message when exiting, you can add the message in exit().

For example,

exit(“you exited the environment”).


2.Using quit method:

This method uses the keyword ‘quit’. You can use this keyword even in print statement.

#Python program to use ‘quit’ to exit a program.

#get a input ‘a’

a = int(input(“enter a number”))

if a>5 :

   print(quit)

else :

  print(a)

This program checks the given number is greater than 5. If yes, it quits the program. Otherwise, it prints the number.


3.Use sys.exit() method:

          This method uses a built in module “sys”.

#Python program using sys.exit() function to exit a program

import sys

id = int(input(" Enter the id"))

if id > 20 :

    sys.exit("you exceeded the limit")

else :

    print("You are in the limit. your id is:",id)#First, import the sys module.

When executing this program, you get the below output.

These are simple methods to exit a python program. Happy coding!!!!



No comments:

Post a Comment