Python的嵌套循环麻烦
我有问我每周实验室的一个问题:Python的嵌套循环麻烦
编写使用嵌套的循环来收集数据,计算 平均温度在数月的计划。该方案应该首先要求月份的数量为 。外循环将每月循环一次 。内部循环将重复执行四次,每月一次,每次执行一次 。内循环的每次迭代将询问用户 该周的平均温度。在所有迭代之后, 程序应该显示每个月的平均温度,以及整个时间段(所有月份)的平均温度。
这是我想出了迄今为止代码:
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)
我似乎无法工作如何获得它,以显示每个月的月平均值。理想情况下,我会使用一个列表,只是附加条目,但因为这是一个介绍类,我们还没有被“教”列表,因此不能使用它们。因此,使用我上面提到的工具,你有什么建议来获得我想要的输出?
把print (monthly_avg)
放在你的外部循环(月循环)中。
当前,您只能打印最后的monthly_avg
。此外,您需要在每月迭代时重置monthly_avg的值。
这确实不会使OP的代码实际上按照他们的意图工作,但我承认这是一个好的开始,并且“显示每个月的月平均值”而不是一次。不过他们会注意到它们并不是很好的平均值! – KernelPanic
根据您的规格,您必须在打印每个月的平均值之前询问所有的值。因此您需要存储每个月的值。
它在概念上更容易存储总计(因此修改后的变量名称)。在打印平均值之前只需执行分部。
# Asks how many months
num_of_months = int(input("Number of Months?: "))
num_of_weeks = 4
# ask and store for weekly values
month_totals = [ 0 ] * num_of_weeks
total = 0
for month in range(num_of_months):
for week in range(num_of_weeks):
week_avg = int(input("Avg week temp?: "))
month_totals[month] += week_avg
total += week_avg
# print averages for each month
for month in range(num_of_months):
month_avg = float(month_totals[month])/float(num_of_weeks)
print (month_avg)
# print average for the entire period
total_avg = float(total)/float(num_of_months * num_of_weeks)
print (total_avg)
您是否浏览过您的教科书,与您的教练说过,与同学讨论过,并在Google上做过一些研究? – TigerhawkT3
一个理想的Stackoverflow问题包括一个MCVE(参见[mcve])。特别是,请编辑您的帖子以包含一些示例输入,您期望的输出以及您实际获得的输出。您也可以从阅读[如何调试小程序]中获益(https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 – KernelPanic