简体   繁体   中英

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.

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

2.in while loop: initialize week_sum=0, then use for loop to ask rainfall of 7 days.

3.Exit for loop ,average the rainfall, and append to the list weekaverage.

4.add week_sum to the total rainfall, and i+=1 to next week

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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