列出整数比较项

2024-10-02 16:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我试图从用户那里得到一个输入,这个输入被添加到一个列表中,然后在我通过另一个函数运行它之前,必须对该列表进行验证。我知道我需要改变一些东西来比较:只能与整数一起使用,并且列表中的输入将是一个字符串。还有一个错误,它说“无序类型:str()>;int()。我该怎么办?在

def strInput():
string = []
string = str(input("Please enter numbers from 1-999... "))
if validate(string):
    return string
else:
    strInput()

def validate(i):
    if i > 0 and i <= 999:
        return True
    else:
        strInput()

Tags: 函数字符串用户列表stringreturnifdef
3条回答

我想收集一份名单给你。下面的代码就可以做到了

def validate(userInput):
    return userInput.isdigit() and int(userInput) > 0 and int(userInput) <= 999

def getListOfNumbers():
    listOfNumbers = []
    while True:
        userInput = raw_input("Please enter a number from 1 to 999. Enter 0 to finish input: ")
        if userInput == '0':
            return listOfNumbers
        elif validate(userInput):
            listOfNumbers.append(int(userInput))
        #optional
        else:
            continue
myList = getListOfNumbers()
print myList

应该是:要么这样做:

if int(i) > 0 and int(i) <= 999:

如果在python3中,input将输入作为字符串
或者这样做:

^{pr2}$

我希望有帮助

def validate(i):
    try:
        num = int(i)
    except:
        return False
    return num > 0 and num <= 999

def strInput():
    string = str(input("Please enter numbers from 1-999... "))
    if validate(string):
        return string
    else:
        return strInput()

strings = []
strings.append(strInput())
strings.append(strInput())
print (strings)

打印出来

^{pr2}$

相关问题 更多 >