Python Forum
Basic Coding Question: Exit Program Command? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Basic Coding Question: Exit Program Command? (/thread-41151.html)



Basic Coding Question: Exit Program Command? - RockBlok - Nov-19-2023

Could anyone provide feedback on the preferred way to terminate a program?

A Google search suggested that there are 3 basic ways to terminate a program.

The three basic methods from Google are:

1. quit()

2. sys.exit("some sort of typed message here")

3. exit()

Thanks for the help!


RE: Basic Coding Question: Exit Program Command? - snippsat - Nov-19-2023

(Nov-19-2023, 04:05 PM)RockBlok Wrote: Could anyone provide feedback on the preferred way to terminate a program?
It's a little vague question,i would say that preferred way is to think about a nice way to exit/terminate of program when write it.
Then many time there is no need to use quit(), exit(), sys.exit() at all,in some cases it may be useful.
A example,so here use a control variable q to exit the loop,also this exit program just bye return out of the function.
def file_deletion():
    file_to_delete = input('File to delete: ')
    print(f'Deleting <{file_to_delete}>\n')
    input('Push enter to retun to menu')

def file_creation():
    pass

def show_menu():
    print ("\nExample menu")
    print ("-----------------")
    print ("1) File deletion")
    print ("2) File creation")
    print ("Q) Exit\n")

def menu():
    while True:
        show_menu()
        choice = input('Enter your choice: ').lower()
        if choice == '1':
            file_deletion()
        elif choice == '2':
            file_creation()
        elif choice == 'q':
            return
        else:
            print(f'Not a correct choice: <{choice}>,try again')

if __name__ == '__main__':
    menu()
Output:
G:\div_code\ur_env λ python meny.py Example menu ----------------- 1) File deletion 2) File creation Q) Exit Enter your choice: car Not a correct choice: <car>,try again Example menu ----------------- 1) File deletion 2) File creation Q) Exit Enter your choice: 1 File to delete: foo.txt Deleting <foo.txt> Push enter to retun to menu Example menu ----------------- 1) File deletion 2) File creation Q) Exit Enter your choice: q G:\div_code\ur_env



RE: Basic Coding Question: Exit Program Command? - Gribouillis - Nov-19-2023

Use sys.exit(), and read the documentation of this function first.


RE: Basic Coding Question: Exit Program Command? - deanhystad - Nov-19-2023

quit(), exit() and sys.exit() are the same, they all raise a SystemExit exception.