简体   繁体   English

Python降雨计算器

[英]Python Rainfall Calculator

I'm trying to solve a problem but I've been working on it for so long and have tried so many things but I'm really new to python and don't know how to get the input I'm after. 我正在尝试解决一个问题,但是我已经研究了很长时间,并且尝试了很多事情,但是我对python真的很陌生,并且不知道如何获得所需的输入。

The calculator needs to be in a format of a nested loop. 计算器必须采用嵌套循环的格式。 First it should ask for the number of weeks for which rainfall should be calculated. 首先,它应询问应计算的降雨周数。 The outer loop will iterate once for each week. 外循环将每周重复一次。 The inner loop will iterate seven times, once for each day of the week. 内循环将迭代7次,一周的每一天一次。 Each itteration of the inner loop should ask the user to enter number of mm of rain for that day. 内循环的每次发声应要求用户输入当天的毫米雨量。 Followed by calculations for total rainfall, average for each week and average per day. 然后计算总降雨量,每周平均和每天平均。

The main trouble I'm having is getting the input of how many weeks there are and the days of the week to iterate in the program eg: 我遇到的主要麻烦是要输入程序中要迭代多少周和一周中的几天,例如:

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

This is the type out output I want but so far I have no idea how to get it to do what I want. 这是我想要的类型输出,但是到目前为止我还不知道如何使它完成我想要的事情。 I think I need to use a dictionary but I'm not sure how to do that. 我想我需要使用字典,但是我不确定该怎么做。 This is my code thus far: 到目前为止,这是我的代码:

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__()

If you can steer me in the right direction I will be so appreciative! 如果您能引导我朝正确的方向前进,我将非常感激!

I use a list to store average rallfall for each week. 我使用列表来存储每周的平均减少量。 and my loop is: 我的循环是:

1.while loop ---> week (using i to count) 1. while循环--->周(用i计数)

2.in while loop: initialize week_sum=0, then use for loop to ask rainfall of 7 days. 2.在while循环中:初始化week_sum = 0,然后使用for循环询问7天的降雨量。

3.Exit for loop ,average the rainfall, and append to the list weekaverage. 3.退出循环,平均降雨量,并附加到列表中的平均值。

4.add week_sum to the total rainfall, and i+=1 to next week 4.将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

Recommendation: Break the problem into smaller pieces. 建议:将问题分解成小块。 Best way to do that would be with individual functions. 最好的方法是使用单个功能。

For example, getting the number of weeks 例如,获取周数

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

Then, getting the mm input for a certain week number and day. 然后,获取特定星期数和日期的毫米输入。 (Here is where your expected output exists) (这是您的预期输出所在的位置)

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

Two functions to calculate the average. 两个函数计算平均值。 First for a list, the second for a list of lists. 第一个用于列表,第二个用于列表。

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

Using those, you can build your weeks of rainfall into their own list. 使用这些,您可以将自己的几周降雨量纳入自己的清单。

# 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

Then, you can write a function that accepts that "master list", and prints out some results. 然后,您可以编写一个接受该“主列表”的函数,并输出一些结果。

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

And, finally, just two lines to run the full script. 最后,只需两行即可运行完整脚本。

weekly_rainfall = get_weekly_rainfall()
print_results(weekly_rainfall)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM