Python 为什么变量不计数';对于每个相应的数字,是否不增加1?

Python 为什么变量不计数';对于每个相应的数字,是否不增加1?,python,list,function,methods,Python,List,Function,Methods,该函数以“温度”列表作为参数,它应该查找并返回正数、负数和零数 def countTemps(temperature): 对于每个温度,相应变量的计数应增加1 temperature=(0, 1, 5, -3, 4, 15, 6, -2, 8, -5, 10, 0, -4, 0, 7) posCount, negCount, zeroCount = 0, 0, 0 integers = 0 对于温度中的整数: 如果整数小于0: 负计数+=1 返回温度 elif整数

该函数以“温度”列表作为参数,它应该查找并返回正数、负数和零数

def countTemps(temperature):
对于每个温度,相应变量的计数应增加1

    temperature=(0, 1, 5, -3, 4, 15, 6, -2, 8, -5, 10, 0, -4, 0, 7)

    posCount, negCount, zeroCount = 0, 0, 0

    integers = 0
对于温度中的整数:
如果整数小于0:
负计数+=1
返回温度
elif整数>0:
posCount+=1
返回温度
其他:
返回温度
零计数+=1
返回温度
打印(“正片数:”,posCount)
打印(“负片数:”,负片计数)
打印(“零的数量:”,零计数)

但是,为什么它们的输出为零而不是正确的计数?

函数
countTemps
到达
return
语句后立即退出。在您的情况下,这意味着循环将增加
zeroCount
一次,然后停止。但是,在函数内部对变量所做的更改在函数外部不可见,因此函数终止后
zeroCount
不会为1

如果删除所有
return
语句,并确保在循环后返回所有计数,则可以捕获函数外部的计数

    for integers in temperature:

        if integers < 0:

            negCount += 1

            return temperature

        elif integers > 0:

            posCount += 1

            return temperature

        else:

            return temperature

            zeroCount += 1

            return temperature

print("Number of Positive: ",posCount)
print("Number of Negative: ",negCount)
print("Number of Zeros: ", zeroCount)

或者,如果您不需要其他地方的计数,您可以将
print
语句移动到函数内部,但在循环之后,并避免使用
return

您想问什么问题吗?是的,我找不到错误。为什么函数中没有返回每个变量的计数?请更新您的问题,包括您期望得到的结果和实际得到的结果,我将尝试回答。这里有一个关于如何提问的指南,函数在到达第一行
返回温度时将立即退出。
def countTemps(temperature):
    ....
    for integers in temperature:
        ....
    return (posCount, negCount, zeroCount)