【问题标题】:Python Nested Loop TroublePython嵌套循环问题
【发布时间】: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


【解决方案1】:

print (monthly_avg) 放入您的外循环(几个月的循环)。

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

【讨论】:

  • 这当然不会让 OP 的代码真正按照他们的预期工作,但我承认这是一个好的开始,并且确实“显示每个月的月平均值”而不是只显示一次。不过,他们会注意到他们并不是很好的平均水平!
【解决方案2】:

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

从概念上讲,存储总数更容易(因此修改了变量名称)。只需在打印平均值之前执行除法即可。

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

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 2021-05-17
    • 2021-11-07
    • 2015-02-14
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    相关资源
    最近更新 更多