gpt4 book ai didi

python - 向列表添加 for 循环

转载 作者:行者123 更新时间:2023-11-28 22:46:39 25 4
gpt4 key购买 nike

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

我不太确定如何添加循环以便计算一周的总销售额。将不胜感激。

最佳答案

试试这个:

total = 0

for store_sale in store_week_sales:
total += store_sale

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

Python 不会区分 for 和(不存在的)foreach,因为 for 已经迭代了可迭代对象的元素, 不超过索引号。

关于python - 向列表添加 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27234076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com