需规避使用max/min函数的Python降雨量统计代码 未匹配对应月份求解决
问题根源
- 现有代码只记录了最大、最小降雨量的数值,没有同步留存该数值对应的月份信息,所以打印的时候只能输出雨量数字,没法报出具体是哪个月。
- 原代码输入环节有个容易踩坑的命名问题:把用户输入的降雨量值存进了叫
month的变量,和代表月份编号的months列表语义混淆,写多了很容易出逻辑bug。
修复方案
- 新增两个变量,分别存最大、最小降雨量对应的月份号,初始化的时候直接拿第一个月的数值和月份绑定作为初始值。
- 遍历雨量列表找极值的时候,只要遇到比现有极值更大/更小的雨量,就同时更新两个内容:极值的雨量值、这个值对应的月份号。
- 最后打印极值信息的时候,输出提前存好的月份号,不要直接输出雨量值。
修复后完整代码
'''this code will get rainfall amount for a given month from the user and calculate the total and find the largest and smallest rainfall month plus the average rainfall.''' #create the variables and list months = [1,2,3,4,5,6,7,8,9,10,11,12] total = 0 average = 0 amounts = [] #set up the loop to get user input #for the rainfall amount of each #month. for i in range(len(months)): # 修正变量命名:存储用户输入的降雨量,而非月份号 rainfall = int(input("Enter the rainfall for month " + str(months[i])+ ":")) while rainfall <=0: print("ERROR! Wrong Value! Try Again") rainfall = int(input("Enter the rainfall for month " + str(months[i])+ ":")) amounts.append(rainfall) #calculate the total total += rainfall #calculate the average average = total / 12 '''calculate the month with the most and least rainfall''' # 初始化时同时记录极值和对应月份 largest_rain = amounts[0] largest_month = months[0] smallest_rain = amounts[0] smallest_month = months[0] for i in range(1, len(amounts)): if amounts[i] > largest_rain: largest_rain = amounts[i] largest_month = months[i] # 同步更新最大值对应的月份 if amounts[i] < smallest_rain: smallest_rain = amounts[i] smallest_month = months[i] # 同步更新最小值对应的月份 print("The total is " + str(total)+ " inches") print("The average is " + str(average)+ " inches") print(f"降雨量最高的月份是 {largest_month} 月,对应降雨量 {largest_rain} 英寸") print(f"降雨量最低的月份是 {smallest_month} 月,对应降雨量 {smallest_rain} 英寸")
修复后运行效果(匹配原示例输入)
Enter the rainfall for month 1:4 Enter the rainfall for month 2:5 Enter the rainfall for month 3:6 Enter the rainfall for month 4:7 Enter the rainfall for month 5:8 Enter the rainfall for month 6:9 Enter the rainfall for month 7:25 Enter the rainfall for month 8:26 Enter the rainfall for month 9:11 Enter the rainfall for month 10:1 Enter the rainfall for month 11:10 Enter the rainfall for month 12:12 The total is 124 inches The average is 10.333333333333334 inches 降雨量最高的月份是 8 月,对应降雨量 26 英寸 降雨量最低的月份是 10 月,对应降雨量 1 英寸
内容的提问来源于stack exchange,提问作者user15308753
相关产品推荐
相关产品推荐

