我在需要查找用户输入总数时遇到问题。但是当我这样做时,它只输出最后一个用户输入。这就是我得到的。
#Ask for the number of days of weather data they have
weather = int(input("How many days of weather data do you have? "))
total=0
x=1
#Ask what the rainfall was for each day
while(x<=weather):
temp_weather = input("What is the rainfall for day " +str(x)+"? ")
x=x+1
#Add the total rainfall output
while(temp_weather>total):
total= total+temp_weather
print("The total rainfall for the period was "+ str(weather))
答案 0 :(得分:0)
temp_weather
。记录最后一个之前的输入然后丢弃。
尝试类似:
#Ask what the rainfall was for each day
while(x<=weather):
total += input("What is the rainfall for day " +str(x)+"? ")
x += 1
print("The total rainfall for the period was "+ str(total))
请注意,我在最后一行将“天气”更改为“总数”,因为我认为这就是您的意图!
答案 1 :(得分:0)
temp_weather
应存储值列表。这意味着它必须是一个列表。在当前代码中,while
循环迭代x
次,但每次都会覆盖temp_weather
变量。因此它只存储最后一个值。
将temp_weather
声明为以下列表:
temp_weather = []
现在,将代码更改为:
while x <= weather:
y = input("What is the rainfall for day " +str(x)+"? ")
temp_weather.append(int(y))
x=x+1
现在,temp_weather
将包含值列表。要获得总计,您只需使用sum()
方法:
total = sum(temp_weather)