[英]How to validate array for negative # and alpha input in Python
我正在嘗試驗證一系列用戶輸入(每小時7小時每小時收集的血滴)的負數,空格和/或字母。 當前,如果使用if語句檢查用戶輸入是否低於0,則程序會收到類型錯誤:“'list'和'int'的實例之間不支持''<'。”
inputPints = []
totalPints = 0
hours = ["#1", "#2", "#3", "#4", "#5", "#6", "#7"]
def userInput():
for hour in hours:
inputPints.append(int(input("Enter pints collected for hour {}: ".format(hour))))
if inputPints<0:
inputPints.append(int(input("Please enter a whole number {}: ".format(hour))))
userInput()
def userOutput():
print("")
print("Average number of pints donated is: ", "{:.2f}".format(import_functions.averagePints(totalPints, 7)))
print("Most pints donated is: ", import_functions.maxPints())
print("Least pints donated is: ", import_functions.minPints())
print("")
userOutput()
您可以使用正則表達式來驗證輸入。 要僅允許格式#number.numbers,可以使用以下示例:
# test for matches on the regex expression.
if len(re.findall('^#\d+.\d+$', "#-1.30")) > 0:
# It is valid
return true
我認為您應該像這樣定義userInput()
方法……
def userInput():
for hour in hours:
user_input = -1
while user_input < 0:
try:
user_input = int(input("Enter pints collected for hour {}: ".format(hour)))
except:
user_input = -1
if user_input > -1:
inputPints.append(user_input)
正如Torxed所評論的,您正在比較“列表”類型的對象與“ int”類型的對象。 這會引起錯誤:
'list'和'int'的實例之間不支持'<'
您應該在將用戶輸入追加到列表之前先對其進行驗證,或者可以遍歷整個列表以查找錯誤/正確的輸入。
在追加之前檢查輸入:
if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
#This is ok
檢查輸入的完整列表
for a in inputPints:
if int(a) > 1:
#a is OK.
我建議您將這些驗證放入try catch塊中,因為如果int()轉換檢測到不可廣播的字符,則它可能會破壞您的代碼。
希望這可以幫助!
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.