我正试图解决一个问题,但我已经研究了很长时间,尝试了很多东西,但是我对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__()如果你能引导我朝着正确的方向前进,我会非常感激的!
发布于 2016-08-12 04:34:27
建议:将问题分解成较小的部分。最好的方法是使用单独的功能。
例如,获得的周数
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)发布于 2016-08-12 04:30:42
我用一个列表来存储每周的平均涨势。我的循环是:
1.同时循环
2.在then循环中:初始化week_sum=0,然后使用for循环询问7天的降雨量。
3.退出循环,平均降雨量,并附加到每周平均名单。
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+=1https://stackoverflow.com/questions/38909156
复制相似问题