Search code examples
pythonpython-3.xuser-inputexitstop-words

Is there a better way to check if a series of inputs match a certain stop condition?


(Python 3.7)

I have a similar program to what's included below. I was just trying to figure out if there is a better way to check if any user input matches an "end" condition, I do need to save each input separately.

while True:
    fname = input("Enter Customer first name: ")
    if fname == "end":
        break
    
    lname = input("Enter Customer last name: ")
    if lname == "end":
        break

    email = input("Enter Customer email: ")
    if email == "end":
        break

    num = input("Enter Customer id: ")
    if num == "end":
        break
    elif not num.isdigit():
        num = -1
    # not worried about error here
    num = int(num)

    print(fname, lname, email, num)
print("User has ended program")

I'm not worried about errors at this stage just trying to brainstorm here about the cleanest implementation. I will have a lot of inputs so I'm hoping I won't have to include the same if statement over and over again for each individual input.


Solution

  • This would be a good opportunity to create a user exception:

    class UserExit(BaseException):
        pass
    
    def get_input(prompt):
        response = input(prompt)
        if response=="end":
            raise UserExit("User Exit.")
        return response
    
    try:
        while True:
            fname = get_input("Enter Customer first name: ")
            lname = get_input("Enter Customer last name: ")
            email = get_input("Enter Customer email: ")
            num = get_input("Enter Customer id:")
            if not num.isdigit():
                num = -1
            else:
                num = int(num)
            print (fname,lname,email,num)
    
    except UserExit as e:
        print ("User ended program.")