类型错误:无序类型:function()>int()

2024-09-24 10:22:11 发布

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

我不知道为什么在我的if statements中,在for loops中,它认为它们是不可排序的类型,以便进行比较。我得到的确切错误如下:

Traceback (most recent call last):
  File "/Users/me/Documents/Eclipse/Week6/src/numbers.py", line 44, in <module>
    myDict = {'AvgPositive':posNumAvg(numInput), 'AvgNonPos':nonPosAvg(numInput),                'AvgAllNum':allNumAvg(numInput)}     
  File "/Users/me/Documents/Eclipse/Week6/src/numbers.py", line 30, in posNumAvg
    if num > 0:
TypeError: unorderable types: function() > int()

我的代码如下:

#While loop function for user input
def numInput():
    numbers = []

    while True:
        num = int(input('Enter a number (-9999 to end):'))
        if num == -9999:
            break
        numbers.append(num)
    return numbers

#Average of all numbers function
def allNumAvg(numList):
    return sum(numList) / len(numList)


#Average of all positive numbers function
def posNumAvg(numList):
    for num in [numList]:
        if num > 0:
            posNum = sum(num)
            posLen = len(num)
    return posNum / posLen

#Avg of all negative numbers function
def nonPosAvg(numList):
    for num in [numList]:
        if num < 0:
            negNum = sum(num)
            negLen = len(num)
    return negNum / negLen

#Creates Dictionary
myDict = {'AvgPositive':posNumAvg(numInput), 'AvgNonPos':nonPosAvg(numInput), 'AvgAllNum':allNumAvg(numInput)}   

#Prints List
print ('The list of of all numbers entered is\n', numInput(),'\n')

#Prints Dictionary
print ('The dictionary with averages is\n', myDict)

我知道我遗漏了一些基本概念。


Tags: ofinforreturnifdeffunctionall
1条回答
网友
1楼 · 发布于 2024-09-24 10:22:11

numInput是一个函数,但在定义myDict时,如果将其传递给posNumAvg,则不会调用它:

posNumAvg(numInput)

该函数作为局部变量传递给posNumAvg,然后是num,然后与始终引用该函数的0进行比较。函数和数字不能比较,这就是你看到的错误。

您可能只需要调用函数,如下所示:

posNumAvg(numInput())

相关问题 更多 >