为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯709654 2021-08-11 22:42:32
我有以下代码,它将询问用户每个月的降雨量,并将其附加到rainfall_inch列表中,并计算average 但我有两个问题1) 在用户输入一个数字和下一个输入运行后,上一个输入显示在下一个输入后面。"Enter rainfallJanuary  :  3Enter 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 averagemain()帮助谢谢
查看完整描述

2 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

在这里,我已经修复了您的代码的一些逻辑错误,请查找注释以查看位置,


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 average


main()

输出:


Enter rainfallJanuary :  40

Enter rainfallFebruary :  50

Enter rainfallMarch :  30

Enter rainfallApril :  60

Enter rainfallMay :  50

Enter rainfallJune :  30

Enter rainfallJuly :  330

Enter rainfallAugust :  20

Enter rainfallSeptember :  50

Enter rainfallOctober :  90

Enter rainfallNovember :  30

Enter 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


查看完整回答
反对 回复 2021-08-11
?
交互式爱情

TA贡献1712条经验 获得超3个赞

我已经像这样删除了 range()

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

并发现工作没有错误


查看完整回答
反对 回复 2021-08-11
  • 2 回答
  • 0 关注
  • 162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信