如何用用户输入附加列表

时间:2018-11-09 04:48:30

标签: python python-3.x list loops input

我有以下代码,该代码将询问用户每个月的降雨量,并将其附加到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()

帮助谢谢

2 个答案:

答案 0 :(得分:1)

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

from flask import Flask, abort, request, jsonify


from models import Categories

from flask_restful import Resource

app = Flask(__name__)

class pagination(Resource):

    url= '/getbypages'
    start=1
    limit=20
    def get(start,limit):
        results = [1,2,3,4,5,6,7,8,9,10]
        print("resultsllllllllllll",results)
        count = len(results)
        obj = {}
        if count < 1:
            print("404")
        else:
            #count = limit-start
            #print(count)
            obj['start'] = start
            obj['limit'] = limit
            obj['count'] = count
            print(obj)
            if start == 1:
                obj['previous'] = ''
            else:
                start_copy = max(1, start - limit)
                print(start_copy)
                limit_copy = start - 1
                obj['previous'] = url + '?start=%d&limit=%d' % (start_copy, limit_copy)
                if start + limit > count:
                    obj['next'] = ''
                else:
                    start_copy = start + limit
                    obj['results'] = results[(start - 1):(start - 1 + limit)]
        return obj
    print(get(start, limit))

输出:

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()

答案 1 :(得分:0)

我已经删除了range()

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

发现没有错误