这是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
我不太确定如何添加循环以便我可以计算一周的总销售额。非常感谢帮助。
答案 0 :(得分:3)
试试这个:
total = 0
for store_sale in store_week_sales:
total += store_sale
print "Total week sales: %.2f" % total
Python在for
和(不存在的)foreach
之间没有区别,因为for
已经迭代了可迭代的元素,而不是遍及索引号。
答案 1 :(得分:1)
如果您绝对想要使用for循环,可以这样做 heltonbiker描述。或者,您可以使用函数sum来完成。
sumOfList = sum(store_week_sales);
由于这是for循环的练习,这可能不是你想要的那个,但知道以备将来参考可能会很好。
答案 2 :(得分:0)
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()