如何在Python中验证数组的负#和alpha输入

2024-04-24 05:26:54 发布

您现在位置: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()

Tags: importformatifisdeffunctionsintprint
3条回答

您可以使用regex验证您的输入。 只允许窗体#数字。数字,您可以使用以下示例:

# test for matches on the regex expression. 
if len(re.findall('^#\d+.\d+$', "#-1.30")) > 0:
    # It is valid
    return true

正如Torxed所评论的,您正在比较“list”类型的对象与“int”类型的对象。这会导致错误:

'<' not supported between instances of 'list' and 'int'

你应该在将用户输入附加到列表之前验证它,或者你可以在整个列表中循环查找错误/正确的输入。在

附加前检查输入:

if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
    #This is ok

用完整列表检查输入

^{pr2}$

如果你检测到一个非castable字符,我建议你尝试将一个非castable()放入一个castable中,因为你可以尝试将一个非castable()代码放入castable中。在

希望这有帮助!在

问候

我认为您应该像这样定义您的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)

相关问题 更多 >