'How to exit a program if a blank line is entered?

I just want to exit the program if a blank line is entered. What do I need?

I've tried sys.exit(), but that doesn't quit the program, just returns a blank

while True: # Ask for patient ID
        try:
            i = int(input("Enter patient ID (or blank to exit): "))
            if not i:
                sys.exit()
            else:
                a = len(str(abs(i))) # Checking valid integer
                if a != 6: # Checking id is six digits
                    print("Enter valid patient ID (six digit positive integer)")
                else:
                    break
        except ValueError:
            print("Enter valid patient ID (six digit positive integer)")

I just expect the program to quit.



Solution 1:[1]

Your mistake was that you were reading and converting the input immediately into an integer! You need to check for blank input in a string format and then convert it to a number.

import sys

while True: # Ask for patient ID


        try:

            #Get the user's input as a string.
            inpu   = input("Enter patient ID (or blank to exit): ")

            #If it's blank, exit.
            if inpu == "":
                sys.exit(0)

            else:

                #Now convert the inputed string into an integer.
                i      = int(inpu)
                a      = len(str(abs(i))) # Checking valid integer

                if a != 6: # Checking id is six digits
                    print("Enter valid patient ID (six digit positive integer)")
                else:
                    break

        except ValueError:
            print("Enter valid patient ID (six digit positive integer)")

Solution 2:[2]

In case of error : sys.exit(1) Else in case of successful run u can use sys.exit() or sys.exit(0)

But your code should be like :

    while True: # Ask for patient ID
        try:
            i = raw_input("Enter patient ID (or blank to exit): ")
            if len(i) == 0:
                sys.exit()
            else:
                a = len(str(abs(i))) # Checking valid integer
                if a != 6: # Checking id is six digits
                    print("Enter valid patient ID (six digit positive integer)")
                else:
                    break
        except ValueError:
            print("Enter valid patient ID (six digit positive integer)")

Maybe replace raw_input by input

Hope that can help you,

Have a good day.

Solution 3:[3]

In python, that's kinda easy..!! :-

import os
val = input("TYPE IN HERE: ")
if val and (not val.isspace()):
    print (val)
else:
    #print("BLANK")
    os._exit(1)

Answer Credit

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 babaliaris
Solution 2
Solution 3 athrvvv