Validating user input strings in Python -


so i've searched every permutation of words "string", "python", "validate", "user input", , on, i've yet come across solution that's working me.

my goal prompt user on whether or not want start transaction using strings "yes" , "no", , figured string comparison easy process in python, isn't working right. using python 3.x, input should taking in string without using raw input, far understand.

the program kick invalid input, when entering 'yes' or 'no', weird thing every time enter a string > 4 characters in length or int value, check valid positive input , restart program. have not found way valid negative input.

endprogram = 0; while endprogram != 1:      #prompt new transaction     userinput = input("would start new transaction?: ");     userinput = userinput.lower();      #validate input     while userinput in ['yes', 'no']:         print ("invalid input. please try again.")         userinput = input("would start new transaction?: ")         userinput = userinput.lower()      if userinput == 'yes':         endprogram = 0     if userinput == 'no':         endprogram = 1 

i have tried

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

i appreciate not problem, if has additional information on how python handles strings great.

sorry in advance if else has asked question this, did best search.

thanks all!

~dave

you testing if user input is yes or no. add not:

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

ever faster , closer intent, use set:

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

what used userinput in ['yes', 'no'], true if userinput either equal 'yes' or 'no'.

next, use boolean set endprogram:

endprogram = userinput == 'no' 

because verified userinput either yes or no, there no need test yes or no again set flag variable.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -