2014-07-16 44 views
0

如果用戶輸入的數字低於下面的值,如何使我的代碼循環回到輸入(並再次檢查值) 0或高於100或沒有輸入整數在Python中,如果用戶輸入的值不正確,我如何使輸入驗證保持循環

NameList = [] 
Name1List = [] 
def Va(): 
    while True: 
     try: 
      int(NameMSplit[1]) 
      if int(NameMSplit[1]) > 0 and int(NameMSplit[1]) < 100: 
       return NameMSplit[1] 
      else: 
       print ("Number is not between 0 and 100") 
     except ValueError: 
      print("Please make sure it's a number ") 

#Main Code 
NameMarks = input("Please input your name followed by your marks seperated by spaces ") 
NameMSplit = NameMarks.split() 
V = Va() 
while NameMarks != 'Q': 
    Name =(NameMSplit[0]) 
    Name1 = (NameMSplit[1]) 
    NameList.append(Name) 
    Name1List.append(Name1) 
    NameMarks = input("Please input your name followed by your marks seperated by spaces ") 
    NameMSplit = NameMarks.split() 
print (Name1List, NameList) 
+0

有什麼問題你目前的做法 – sshashank124

+0

如果我輸入類似「GW」它會一遍又一遍地說「請確保它是一個數字」,並且不允許我開始o在輸入處再次輸入,同樣的輸入如「g 101」 – user3459426

回答

0

您可以在您的函數的輸入如下:

def Va(): 
    while True: 
     NameMarks = input("Please input your name followed by your marks seperated by spaces ") 
     NameMSplit = NameMarks.split() 
     try: 
      int(NameMSplit[1]) 
      if int(NameMSplit[1]) > 0 and int(NameMSplit[1]) < 100: 
       return NameMarks 
      else: 
       print ("Number is not between 0 and 100") 
     except ValueError: 
      print("Please make sure it's a number ") 

#Main Code 
NameMarks = Va() 
... 
+0

@ user3459426,在你的主代碼中,將'V = Va()'改爲'NameMarks = Va()',並在你的函數中返回'NameMarks'返回'NameMSplit [1]' – sshashank124

+0

感謝您的幫助到目前爲止,我遇到了一個錯誤,在我的主代碼中,如果我輸入「Q」作爲我的輸入來打印我的列表,我得到一個索引錯誤「List index out範圍「。我還將主代碼的最後兩行更改爲「NameMarks = Va()」 – user3459426