2014-12-01 118 views
2

这是从Python书籍的问题:添加一个for循环列表

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

这是我在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 

我不是如何添加循环,这样我可以calulate总销售额一周的那么肯定。帮助将不胜感激。

+0

东西不直接相关的问题: 你可以做'销售= [INT(输入(“进入店铺销售额%s的:”%天))在['周日白天,“星期一” ,'Tuesday','Wednesday']]' – Santiago 2014-12-01 17:55:04

回答

3

尝试这种情况:

total = 0 

for store_sale in store_week_sales: 
    total += store_sale 

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

Python不使for和(不存在)foreach之间的差,因为for已经超过一个可迭代的元素,没有结束索引号迭代。

+0

谢谢Helton。 – DSmith2014 2014-12-01 18:40:35

1

如果你绝对想用for循环做它,它可以完成像heltonbiker描述的 。或者,你可以用函数和来完成它。因为它是for循环的练习,这可能不是你这次寻找的东西,但它可以很好地知道以备将来参考。

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

请添加一些叙述来解释您倾倒在我们身上的代码是干什么以及如何/为什么。 – 2017-04-10 20:27:09