【发布时间】:2017-03-08 03:43:37
【问题描述】:
我的每周实验室有一个问题,询问:
编写一个程序,使用嵌套循环来收集数据并计算 几个月的平均温度。该程序应 首先询问月数。外循环将迭代一次 每个月。内部循环将迭代四次,每次一次 一个月中的一周。内部循环的每次迭代都会询问用户 为该周的平均温度。在所有迭代之后, 程序应该显示每个月的平均温度,并且对于 整个期间(所有月份)。
这是我迄今为止想出的代码:
def avgTemp():
'''This function takes the input of number of months and takes 4 weekly temp averages
for each month then prints out the whole average
num_of_month --- integer
week_temp --- integer
total_avg --- return'''
num_of_month = int(input("Number of Months?: ")) #Asks how many months
total_avg = 0
monthly_avg = 0
for number in range(0,num_of_month):
for week in range(0,4):
week_temp = int(input("Avg week temp?: "))
monthly_avg += week_temp
monthly_avg = monthly_avg/4
total_avg += monthly_avg
total_avg = total_avg/num_of_month
print (total_avg)
print (monthly_avg)
我似乎无法弄清楚如何让它显示每个月的月平均值。理想情况下,我会使用一个列表并只附加条目,但因为这是一个介绍类,我们还没有被“教”过列表,因此不能使用它们。那么,使用我上面的工具,你有什么建议可以得到我想要的输出?
【问题讨论】:
-
你有没有复习过你的教科书,和你的导师谈过,和你的同学讨论过,并在谷歌上做过一些研究?
-
一个理想的 Stackoverflow 问题包括一个 MCVE(参见 minimal reproducible example)。特别是,请编辑您的帖子以包含一些示例输入、您期望的输出以及您实际获得的输出。你也可以从阅读How to debug small programs 中受益。
标签: python python-3.x for-loop nested-loops