用户输入标准差程序时出错

时间:2016-02-04 08:13:05

标签: python logic

我的程序用于计算用户给出的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) 

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误。 通过阅读代码生成的错误消息,您可以轻松找到它:

  1. 在函数平均值

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

  2. 列出追加

    请勿使用例如   sqDiff[x] = (values[x] - av)**2 你可以在使用dict而不是列表时执行此操作!由于python无法确定是否会连续分配列表索引而是使用sqDiff.append(...)

  3. 不要使用浮点数连接字符串。我建议阅读PEP 0498 (https://www.python.org/dev/peps/pep-0498/),它让你了解如何在python中形成字符串

相关问题