Validating custom string input in Python

So, I searched for almost every permutation of the words "string", "python", "validate", "user input", etc., but I still have to find a solution that works for me.

My goal is to ask the user if they want to start another transaction using the yes and no strings, and I decided that string comparison would be a fairly simple process in Python, but something just isn’t Right. As far as I understand, I'm using Python 3.X, so the input should be perceived in a line without using raw input.

The program always discards invalid input, even when you enter yes or no, but it is really strange that every time I enter aa> 4 characters in length or an int value, it checks this as a valid positive input and restarts the program . I did not find a way to get a valid negative input.

endProgram = 0;
while endProgram != 1:

    #Prompt for a new transaction
    userInput = input("Would you like to start a new transaction?: ");
    userInput = userInput.lower();

    #Validate input
    while userInput in ['yes', 'no']:
        print ("Invalid input. Please try again.")
        userInput = input("Would you like to start a new transaction?: ")
        userInput = userInput.lower()

    if userInput == 'yes':
        endProgram = 0
    if userInput == 'no':
        endProgram = 1

I also tried

while userInput != 'yes' or userInput != 'no':

I would really appreciate not only helping with my problem, but also that someone has additional information on how Python handles strings that would be large.

Sorry if someone else asked such a question, but I did my best to perform a search.

Thanks everyone!

~ Dave

+2
source share
2 answers

You are testing if the user enters yes no. not:

while userInput not in ['yes', 'no']:

- :

while userInput not in {'yes', 'no'}:

, , userInput in ['yes', 'no'], True, userInput 'yes' 'no'.

boolean endProgram:

endProgram = userInput == 'no'

, userInput yes no, yes no , .

+8
def transaction():

    print("Do the transaction here")



def getuserinput():

    userInput = "";
    print("Start")
    while "no" not in userInput:
        #Prompt for a new transaction
        userInput = input("Would you like to start a new transaction?")
        userInput = userInput.lower()
        if "no" not in userInput and "yes" not in userInput:
            print("yes or no please")
        if "yes" in userInput:
            transaction()
    print("Good bye")

#Main program
getuserinput()
+1

All Articles