简体   繁体   中英

Python - Validation checks on an input

Currently I am writing some validation code for an input in my program and I cannot seem to get the error message to display correctly!

I have my types defined in a string list like this:

types = ['Guitar','Piano','Drums','Violin','Voice','Flute','Cello','Bass']

Then my code for the validation check is:

    typevalid = False
    while typevalid == False:
      Type =  input("Please enter the tutor type: ").title()
      for count in range (0,7):
        if Type == types[count]:
          typevalid = True
          Tutor = (Name,Type)       
          insert_data(Tutor)
          print("New data added")
          print()
        if Type != types[count]:
          print("!!Please enter a correct type!!\n")
    add = input("Do you wish to add another record? (y/n) ")

I have tried changing and moving the second if Type code and it either repeats the error X amount of times becuase of the range loop or it will display the error message twice.

Any suggestions on how I can get this to work?

A few suggestions:

types = ["guitar", "piano", ...] # note case

while True:
    type_ = str(input("Please enter the tutor type: "))
    if type_.lower() in types: # checks all items in types in one line
        break # leave while loop
    print("Please enter a correct type!") # only happens once per loop

You can add your other functionality around this core logic. If you want the leading capital letters back later, you can use type_.capitalize() .

a couple of problems - types has 8 elements but your for loop goes over range(0,7) . Better to rewrite as for count in range(len(types)):

More significantly, your second if statement doesn't work - it checks one Type each time (either in the loop or out of the loop). What you need to do is check that none have been found. Try this:

typevalid = False
while typevalid == False:
    Type =  input("Please enter the tutor type: ").title()
    for count in range(len(types)):
        if Type == types[count]:
            typevalid = True
            Tutor = (Name,Type)       
            insert_data(Tutor)
            print("New data added")
            print()

    if typevalid == False:
      print("!!Please enter a correct type!!\n")
add = input("Do you wish to add another record? (y/n) ") 

NB: Just seen jonrsharpe's response - it's much cleaner but this may explain what's going wrong in your current code.

You never break out of the loop:

for count in range(0,7):
    if Type == types[count]:
        # need to add the following lines:
        typevalid == True
        break

A few additional suggestions:

  • Rather than looping over types manually, use the builtin membership checking functionality of in

    • Do if Type in types: instead of for count in range(...

    • Better yet, since you are checking types over and over again, it's much more efficient to use a set : set(['Guitar', 'Piano', ...]) , or (in Python 2.7+) simply {'Guitar', 'Piano', ... } .

  • Uppercase variables are conventionally used for class names in python. You should use lower case names instead. If you want to avoid overriding the builtin type variable, use a trailing underscore ( type_ ), or simply make your variable more descriptive (eg tutor_type )

After these suggestions, your code would look something like this:

tutor_types = {'guitar', 'piano', 'drums', 'violin', 'voice', 'flute', 'cello', 'bass'}
while True:
    tutor_type = input('Please enter the tutor type: ').lower()
    if tutor_type in tutor_types:
        # Valid input logic here
        break # don't forget to break out of the loop

    print('The error message the user receives after entering incorrect info!')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM