如何在python中添加用户输入



我正在做一个问题,需要查找用户输入的总数。但当我这样做时,它只输出最后一个用户输入。这是我得到的。

#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)

相关内容

  • 没有找到相关文章

最新更新