2

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.

Serge Ballesta
  • 136,215
  • 10
  • 111
  • 230

3 Answers3

4

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)")
babaliaris
  • 611
  • 7
  • 14
0

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.

PAYRE Quentin
  • 141
  • 11
0

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

athrvvv
  • 9
  • 1
  • 3