猿问

如何使用用户输入附加列表

我有以下代码,它将询问用户每个月的降雨量,并将其附加到rainfall_inch列表中,并计算average 但我有两个问题


1) 在用户输入一个数字和下一个输入运行后,上一个输入显示在下一个输入后面。


"Enter rainfallJanuary  :  3

Enter rainfallFebruary 3 :  4"

等等

2)问题是list我的代码“' '对象不能解释为整数”。


def main():


    rainfall_inch = []


    name_month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]



    for item in name_month:

        x = input()

        print("Enter rainfall" + item, x, ": ", end=' ')

        rainfall_inch.append(x)

    b = [float(x) for x in range(rainfall_inch)]



    print(b)


    print("average rainfall is:", computeAverage(b))


def computeAverage(values):

    #find average of rainfull

    total = 0.0

    for x in values:

        total+=x

    average = total/len(values)

    return average


main()

帮助谢谢


慕斯709654
浏览 163回答 2
2回答

繁星coding

在这里,我已经修复了您的代码的一些逻辑错误,请查找注释以查看位置,def main():    rainfall_inch = []    name_month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]    for item in name_month:        print("Enter rainfall" + item, ": ", end=' ')        x = input()        if x == '':            x = 0        rainfall_inch.append(x) # you are appending here    b = [float(i) for i in rainfall_inch] # so remove the range here, its wrong    # range generates integers from a to b where a and b are integers    print(b)    print("average rainfall is:", computeAverage(b))def computeAverage(values):    #find average of rainfull    total = 0.0    for x in values:        total+=x    average = total/len(values)    return averagemain()输出:Enter rainfallJanuary :  40Enter rainfallFebruary :  50Enter rainfallMarch :  30Enter rainfallApril :  60Enter rainfallMay :  50Enter rainfallJune :  30Enter rainfallJuly :  330Enter rainfallAugust :  20Enter rainfallSeptember :  50Enter rainfallOctober :  90Enter rainfallNovember :  30Enter rainfallDecember :  430[40.0, 50.0, 30.0, 60.0, 50.0, 30.0, 330.0, 20.0, 50.0, 90.0, 30.0, 430.0]average rainfall is: 100.83333333333333

交互式爱情

我已经像这样删除了 range()b = [float(x) for x in rainfall_inch]并发现工作没有错误
随时随地看视频慕课网APP

相关分类

Python
我要回答