计算一周的平均温度。蟒蛇

时间:2014-11-06 00:35:34

标签: python

我是一名新编码员,想知道是否有人能告诉我下面的代码出了什么问题。我试图回答下面的问题而且一直被困住了。如果有人可以提供帮助那就太棒了。

  

编写一个程序,要求用户输入高温   一周的每一天。将温度存储在列表中。一旦   完成后,输出已存储到列表中的所有温度   作为格式化的表格以及本周的平均温度。

week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

print "Day" + (" "*12) + "High Temperature"
print "-"*30
temperature = []
temp = 0
spaces = 0

for i in range (len(week_days)):
    temp_input = input ("Enter the temperature for" +week_days[i]+str(":"))
    temperature.append(temp_input)
    spaces = 15-len(week_days[i])
    print week_days[i]," "*spaces,temperature[i]

avg= 0
list_sum = 0 
for i in range (len(temperature)):
    avg = ((list_sum + temperature[i])-15)/7
    avg = int((avg*100) + 0.5)/100
print "The average temperature for this week is", average
编辑:对不起伙计我修正了错误,但现在我的平均值似乎只是打印3.有什么建议吗?

3 个答案:

答案 0 :(得分:0)

  • Sum是内置函数,它用于计算列表中元素的总和。不确定你想要计算什么,但是如果你想计算温度的总和,你可以这样使用它sum(temperature)

  • 尝试将转换输入添加到int以应用数学运算

如果你能提供更多细节会更好。但是您的代码应该如下所示:

week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

print "Day" + (" "*12) + "High Temperature"
print "-"*30
temperature = []
temp = 0
spaces = 0

for i,x in enumerate(week_days):
    temp_input = input ("Enter the temperature for" +x+str(":"))
    temperature.append(int(temp_input))
    spaces = 15-len(x)
    print x," "*spaces,temperature[i]

avg= sum(temperature)//len(week_days)


print "The average temperature for this week is", avg  

答案 1 :(得分:0)

使用带有str.format的字典,您可以将密钥作为参数传递,并使用Format Specification Mini-Language以您想要的任何方式输出数据:

week_days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

# get user input for each day and convert to ints
temps  = map(int,[raw_input("Enter temp for {}".format(week_days[i])) for i in xrange(7)])
# make dict with days as keys and temps as values
zipped = dict(zip(week_days,temps))

print("Daily Temps:  Monday: {Mon} Tuesday: {Tue} Wednesday: {Wed}"
      " Thursday: {Thu} Friday: {Fri} Saturday: {Sat} Sunday: {Sun}".format(**zipped))

 print("Average Temp for the week: {:.2f}".format(sum(temps) / 7.0))

答案 2 :(得分:0)

您可以使用以下简单代码编写:

day1 = input(“输入mondays temp:”)

day2 =输入(“输入星期二临时:”)

day3 =输入(“输入wednesdays temp:”)

day4 =输入(“输入thursdays temp:”)

day5 =输入(“输入fridays temp:”)

day6 =输入(“输入星期六临时:”)

day7 =输入(“输入星期日临时:”)

av =(day1 + day2 + day3 + day4 + day5 + day6 + day7)/ 7

print“平均温度”,av 23