Python嵌套循环麻烦

时间:2017-03-08 03:43:38

标签: python python-3.x for-loop nested-loops

我的每周实验室有一个问题:

  

编写一个使用嵌套循环来收集数据和计算的程序   几个月的平均温度。该计划应该   首先询问月数。外循环将迭代一次   每个月。内循环将迭代四次,每次一次   一周一个星期。内循环的每次迭代都会询问用户   对于那一周的平均温度。在所有迭代之后,   程序应显示每个月的平均温度,并为   整个时期(所有月份)。

这是我到目前为止提出的代码:

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)

我似乎无法弄清楚如何让它显示每月的月平均值。理想情况下,我会使用一个列表,只是附加条目,但因为这是一个介绍类,我们还没有被教过"列表尚未列出,因此无法使用它们。那么,使用我上面提到的工具,你有什么建议来获得我想要的输出?

2 个答案:

答案 0 :(得分:1)

print (monthly_avg)放入外循环(循环数月)。

目前,您只打印最后一个monthly_avg。此外,您需要在每月迭代时重置monthly_avg的值。

答案 1 :(得分:0)

根据您的规范,您必须在打印每个月的平均值之前询问所有值。因此,您需要存储每个月的值。

概念上更容易存储总计(因此修改后的变量名称)。只需在打印平均值之前执行分割。

# 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)