簡體   English   中英

Python-對輸入進行驗證檢查

[英]Python - Validation checks on an input

目前,我正在為程序中的輸入編寫一些驗證代碼,但似乎無法正確顯示錯誤消息!

我在這樣的字符串列表中定義了我的類型:

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

然后,我用於驗證檢查的代碼是:

    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) ")

我嘗試更改和移動第二個if Type代碼,它要么由於范圍循環而重復錯誤X次數,要么將顯示兩次錯誤消息。

關於如何使它起作用的任何建議?

一些建議:

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

您可以圍繞此核心邏輯添加其他功能。 如果您想稍后再返回大寫字母,可以使用type_.capitalize()

幾個問題- types具有8個元素,但是您的for循環超過range(0,7) 最好重寫為for count in range(len(types)):

更重要的是,您的第二條if語句不起作用-每次(在循環中或循環外)都檢查一個Type 您需要做的是檢查未找到任何內容。 嘗試這個:

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) ") 

注意:剛剛看到jonrsharpe的響應-干凈得多,但這可以解釋您當前代碼中出了什么問題。

您永遠不會脫離循環:

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

一些其他建議:

  • 與其手動循環types ,不如使用in的內置成員資格檢查功能

    • if Type in types:而不是for count in range(...

    • 更好的是,由於您要一遍又一遍地檢查types ,因此使用setset(['Guitar', 'Piano', ...])或(在Python 2.7+中)簡單地使用{'Guitar', 'Piano', ... }

  • 大寫變量通常用於python中的類名。 您應該改用小寫字母名稱。 如果要避免覆蓋內置的type變量,請使用下划線( type_ ),或者只是使變量更具描述性(例如tutor_type

這些建議之后,您的代碼將如下所示:

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!')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM