平均温度

时间:2018-11-10 19:39:10

标签: python

我的程序遇到了麻烦,因为它没有列出年份和温度。另外,如何打印一条消息,说明温度比前一年有所升高?

这是我的代码:

years = int(input('How many years do you want to calculate the temperature outside?'))
first = int(input('What year would you want to start calculating?'))
month = 12
for year in range(1, years, + 1):
    for months in range(1, 13):
     get = float(input('What is the average temperature for month {} '.format(months)))
     if get < -100 or get > 200:
      print('Repeat a valid number.')
     get += get + months
     get = get / 12
print('Years\tTemperature')
print('-------------------')
print(years, '\t', format(get, '.2f'), sep ='')

1 个答案:

答案 0 :(得分:0)

如果首先将所有用户输入存储在列表中,然后进行处理并随后打印结果,则将相对容易。

这样做时,您可以跳过检查上一年度的平均值,方法是先给它一个初始值None,然后在计算以确定是否有所增加时对其进行检查。

这是我的意思:

years = int(input('How many years do you want to calculate the temperature outside? '))
first = int(input('What year would you want to start calculating? '))
data = []

for year in range(first, first+years):
    print('\nEnter temperatures for year', year)
    month_temps = []
    for month in range(1, 13):
        prompt = "What's the average temperature for month {}? ".format(month)
        # Loop until user enters a valid monthly temperature.
        while True:
            try:
                avg_temp = float(input(prompt))
            except ValueError:
                print("Sorry, didn't understand that, try again.")
                continue
            if -100 <= avg_temp <= 200:  # Valid number?
                break
            else:
                print("Sorry, but that's not valid, try again.")
                continue
        month_temps.append(avg_temp)

    # Compute the year's average temperature from the monthly ones.
    avg_temp = sum(month_temps) / len(month_temps)
    data.append((year, avg_temp))

print()
fmt_spec = '{:<4} {:>22} {:>16}'
print(fmt_spec.format('Year', 'Temperature', 'Increase'))
prev_temp = None
for year, avg_temp in data:
    difference = (avg_temp - prev_temp) if prev_temp is not None else 0
    print(fmt_spec.format(year, avg_temp, 'Yes' if difference > 0 else ''))
    prev_temp = avg_temp
相关问题