Python降雨计算器

时间:2016-08-12 02:59:27

标签: python calculator

我正在尝试解决一个问题,但我已经研究了很长时间并尝试了很多东西,但我真的很新的python而且不​​知道如何获取我之后的输入

计算器需要采用嵌套循环的格式。首先,它应该询问应该计算降雨量的周数。外循环将每周迭代一次。内循环将迭代七次,每周一次。内循环的每次迭代都应该要求用户输入当天的降雨天数。然后计算总降雨量,每周平均值和每天平均值。

我遇到的主要问题是获取有多少周的输入以及一周中的日期来迭代程序,例如:

Enter the amount of rain (in mm) for Friday of week 1: 5
Enter the amount of rain (in mm) for Saturday of week 1: 6
Enter the amount of rain (in mm) for Sunday of week 1: 7
Enter the amount of rain (in mm) for Monday of week 2: 7
Enter the amount of rain (in mm) for Tuesday of week 2: 6

这是我想要的输出输出,但到目前为止我不知道如何让它做我想要的。我想我需要使用字典,但我不知道该怎么做。到目前为止,这是我的代码:

ALL_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
total_rainfall = 0
total_weeks = 0
rainfall = {}

# Get the number of weeks.
while True:
    try:
        total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: "))
    except ValueError:
        print("Number of weeks must be an integer.")
        continue

    if total_weeks < 1:
        print("Number of weeks must be at least 1")
        continue
    else:
        # age was successfully parsed and we're happy with its value.
        # we're ready to exit the loop!
        break

for total_rainfall in range(total_weeks):
    for mm in ALL_DAYS:
        mm = int(input("Enter the amount of rain (in mm) for ", ALL_DAYS, "of week ", range(total_weeks), ": "))
        if mm != int():
            print("Amount of rain must be an integer")
        elif mm < 0 :
            print("Amount of rain must be non-negative")

    # Calculate totals.
    total_rainfall =+ mm
    average_weekly = total_rainfall / total_weeks
    average_daily = total_rainfall / (total_weeks*7)
  # Display results.
    print ("Total rainfall: ", total_rainfall, " mm ")
    print("Average rainfall per week: ", average_weekly, " mm ")
    print("Average rainfall per week: ", average_daily, " mm ")

    if __name__=="__main__":
        __main__()

如果你能引导我朝着正确的方向前进,我将非常感激!

2 个答案:

答案 0 :(得分:0)

我使用一个列表来存储每周的平均rallfall。 我的循环是:

1.while loop ---&gt;一周(使用我计算)

2.in while循环:初始化week_sum = 0,然后使用for循环询问7天的降雨量。

3.退出循环,平均降雨量,并附加到列表weekaverage。

4.add week_sum到总降雨量,i + = 1到下周

weekaverage=[]
i = 0 #use to count week

while i<total_weeks:
    week_sum = 0.
    print "---------------------------------------------------------------------"
    for x in ALL_DAYS:
        string = "Enter the amount of rain (in mm) for  %s of  week #%i : " %(x,i+1)
        mm = float(input(string)) 
        week_sum += mm
    weekaverage.append(weeksum/7.)
    total_rainfall+=week_sum
    print "---------------------------------------------------------------------"
    i+=1

print "Total rainfall: %.3f" %(total_rainfall)
print "Day average is %.3f mm" %(total_rainfall/total_weeks/7.)

a = 0

for x in weekaverage:
    print "Average for week %s is %.3f mm" %(a,x)
    a+=1

答案 1 :(得分:0)

建议:将问题分解成更小的部分。最好的方法是使用个人功能。

例如,获得周数

def get_weeks():
    total_weeks = 0
    while True:
        try:
            total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: "))
            if total_weeks < 1:
                print("Number of weeks must be at least 1")
            else:
                break
        except ValueError:
            print("Number of weeks must be an integer.")

    return total_weeks

然后,获取特定周数和日的mm输入。 (这是您的预期输出存在的位置)

def get_mm(week_num, day):
    mm = 0
    while True:
        try:
            mm = int(input("Enter the amount of rain (in mm) for {0} of week {1}: ".format(day, week_num)))
            if mm < 0:
                print("Amount of rain must be non-negative")
            else:
                break
        except ValueError:
            print("Amount of rain must be an integer")

    return mm

计算平均值的两个函数。首先是列表,第二个是列表。

# Accepts one week of rainfall
def avg_weekly_rainfall(weekly_rainfall):
    if len(weekly_rainfall) == 0:
        return 0
    return sum(weekly_rainfall) / len(weekly_rainfall)

# Accepts several weeks of rainfall: [[1, 2, 3], [4, 5, 6], ...]    
def avg_total_rainfall(weeks):
    avgs = [ avg_weekly_rainfall(w) for w in weeks ]
    return avg_weekly_rainfall( avgs )

使用这些,你可以将你的几周降雨量建立在自己的清单中。

# Build several weeks of rainfall
def get_weekly_rainfall():
    total_weeks = get_weeks()
    total_rainfall = []

    for week_num in range(total_weeks):
        weekly_rainfall = [0]*7
        total_rainfall.append(weekly_rainfall)

        for i, day in enumerate(ALL_DAYS):
            weekly_rainfall[i] += get_mm(week_num+1, day)

    return total_rainfall

然后,您可以编写一个接受“主列表”的函数,并打印出一些结果。

# Print the output of weeks of rainfall
def print_results(total_rainfall):
    total_weeks = len(total_rainfall)
    print("Weeks of rainfall", total_rainfall)

    for week_num in range(total_weeks):
        avg = avg_weekly_rainfall( total_rainfall[week_num] )
        print("Average rainfall for week {0}: {1}".format(week_num+1, avg))

    print("Total average rainfall:", avg_total_rainfall(total_rainfall))

最后,只需要两行来运行完整的脚本。

weekly_rainfall = get_weekly_rainfall()
print_results(weekly_rainfall)