繁体   English   中英

计算列表中项目的总和

[英]calculating sum of items in a list

我正在尝试从用户那里获取输入并将其放入列表中然后计算总数但是我一直收到错误“不可迭代”有代码:

def sales_function():
    month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
    month_sale = []
    for months in month_list :
        user_input = int(input(print("Enter the sales for " + months +":" )))
        month_sale.append(user_input)
    for items in range(len(month_sale)):
        total_sales = sum(items)
        print("Total sales:" + total_sales)

销售函数()

有 2 个问题:输入中的打印和总和的使用:总和的参数是一个可迭代的(列表、元组、...)但是您提供的项目是 integer。这是没有这些错误的代码:

def sales_function():
    month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
    month_sale = []
    for months in month_list :
        user_input = int(input("Enter the sales for " + months +":" ))
        month_sale.append(user_input)
    total_sales = sum(month_sale)
    print("Total sales:", total_sales)

定义你要写的function后需要tab indentation ,为了告诉python定义后的代码就是function的代码。

提示:您应该使用复数名称调用您使用的列表(例如: month_list变为months )并能够使用相应的单数和复数形式进行迭代( for month in months: :)。

当您想查看一个变量的内容时,您不需要调用print function:只需在新的一行中传递您想要查看的变量的名称。

此外,您真的不想将input直接转换为 Python 类型。 例如,如果用户输入字符串“Sup”而不是所需的 integer,当您尝试将“Sup”转换为 integer 时,Python 将抛出异常。这会导致程序执行结束(如果您不使用try except语句手动处理异常)。

对于另一个for循环,您不需要range(len()) ,只需使用for month_sale in month_sales来执行迭代。

在此之后,我猜你想打印所有月销售额的总和。 这里是:

def sales_function():
    months_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
    month_sales = []
    for month in months_list :
        user_input = int(input("Enter the sales for " + month +":" ))
        month_sales.append(user_input)
    
    total_sales = 0
    for month_sale in month_sales:
        total_sales = total_sales + month_sale
    print("Total sales:" + str(total_sales))

我有一个解决方案给你。

   def sales_function():
month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
              'November', 'December']
month_sale = []
for months in month_list:
    user_input = input("Enter the sales for " + months + ":")
    month_sale.append(user_input)
print("Total sales:", len(month_sale))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM