Search code examples
pythonexit-codesys

sys.exit() causes an unexpected error causing the "repl process to die unexpectedly"


I am using repl.it to code a login/registration screen. The code in Python is below:

while True:
    print("""
============MAIN MENU================
                   *Welcome*
                   1. Register
                   2. Login
                   3. Quit
""")
    
    x=input("Enter choice:")
    if int(x)==1:
        register()
    elif int(x)==2:
        login()
    elif int(x)==3:
        print("Goodbye then!")
        sys.exit()

It works fine, but on pressing option 3, it prints goodbye to the screen but then displays this error:

repl process died unexpectedly:

When I have used sys.exit in the past it just resorts to a simple exit (cursor flashing) and no error message.

What have I done wrong, and for teaching purposes, what are best practices here?


Solution

  • I will suggests you change the code to:

    while True:
        print("""
    ============MAIN MENU================
                       *Welcome*
                       1. Register
                       2. Login
                       3. Quit
    """)
        
        x = int(input("Enter choice: "))
        if x == 1:
            register()
        elif x == 2:
            login()
        elif x == 3:
            print("Goodbye then!")
            break
    

    It is not advisable to be using sys.exit() method in an iteration instead break out of the loop and perform all the necessary operation. As to why it raised an error, sys.exit() crashes the operation of the iteration and terminate the program. So it's always a good practice to break out of loop first.