在lis中添加for循环

2024-10-01 11:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这是Python书中的问题:

设计一个程序,要求用户输入一个商店一周中每一天的销售额。金额应存储在列表中。使用循环计算一周的总销售额并显示结果。在

这是到目前为止我在Python代码中看到的:

Sunday = int(input("Enter the store sales for Sunday: "))
Monday = int(input("Enter the store sales for Monday: "))
Tuesday = int(input("Enter the store sales for Tuesday: "))
Wednsday = int(input("Enter the store sales for Wednsday: "))
Thursday = int(input("Enter the store sales for Thursday: "))
Friday = int(input("Enter the store sales for Friday: "))
Saturday = int(input("Enter the store sales for Saturday: "))

store_week_sales = [Sunday, Monday, Tuesday, Wednsday, Thursday, Friday, Saturday]

index = 0

我不太确定如何增加循环,以便计算出一周的总销售额。非常感谢您的帮助。


Tags: thestoreforinputintentersalesmonday
3条回答

如果你真的想用for循环来做,可以这样做 赫尔顿比克描述道。或者,也可以用sum函数来实现。在

sumOfList = sum(store_week_sales);

由于这是for循环中的一个练习,这可能不是您这次要寻找的内容,但是了解它可以作为将来的参考。在

def main():

    total = 0.0
    daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    index = 0

    days_of_the_week = ['Sunday', 'Monday', 'Tuesday', 'Wednsday', 'Thursday', 'Friday', 'Saturday']

    for index in range(7):

        print("Enter the amount of sales for", days_of_the_week[index])
        daily_sales[index] = float(input("Enter the sales here: "))

        total += daily_sales[index]

    print("The total sales for the week is $", format(total, '.2f'), sep = ' ')

main()

试试这个:

total = 0

for store_sale in store_week_sales:
    total += store_sale

print "Total week sales: %.2f" % total

Python在for和(不存在)foreach之间没有区别,因为for已经迭代了iterable的元素,而不是索引号。在

相关问题 更多 >