标准偏差程序的用户输入错误

2024-04-27 04:48:32 发布

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

我的程序是用来计算5个值的标准差由用户给出。在for循环中获取输入时,我的代码有问题。为什么?你知道吗

givenValues = []

def average(values):
for x in range(0, 6):
    total = total + values[x]
    if(x==5):
        average = total/x
        return average

def sqDiff(values):
    totalSqDiff = 0
    sqDiff = []
    av = average(values)
    for x in range(0,6):
        sqDiff[x] = (values[x] - av)**2
        totalSqDiff = totalSqDiff + sqDiff[x]
    avSqDiff = totalSqDiff / 5
    SqDiffSquared = avSqDiff**2
    return SqDiffSquared

for counter in range(0,6):
    givenValues[counter] = float(input("Please enter a value: "))
counter = counter + 1
sqDiffSq = sqDiff(givenValues)
print("The standard deviation for the given values is: " + sqDiffSq) 

Tags: inforreturndefcounterrangetotalvalues
1条回答
网友
1楼 · 发布于 2024-04-27 04:48:32

您的代码中有几个错误。 您可以通过阅读代码生成的错误消息轻松找到:

  1. 在函数平均值中

    插入行total = 0 你在使用它之前先使用它。

  2. 列表追加

    不要使用例如 sqDiff[x] = (values[x] - av)**2 你可以这样做时,使用dict的,但不是名单!由于python无法确保列表索引将被连续分配,因此请改用sqDiff.append(...)

  3. 不要用浮点数连接字符串。我建议读政治公众人物0498 (https://www.python.org/dev/peps/pep-0498/)这让您了解如何在python中格式化字符串

相关问题 更多 >