我正在做一个问题,需要查找用户输入的总数。但当我这样做时,它只输出最后一个用户输入。这是我得到的。
#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))
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))
注意,我在最后一行把"weather"改成了"total",因为我认为这就是你的意图!
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)