Question

I'm doing a problem where I need to find the total of the user input. But when I do it, it only outputs the last user input. Here's what I got.

#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))
Was it helpful?

Solution

temp_weather is being overwritten every subsequent time the user inputs information. The inputs before the last one are being recorded and then discarded.

Try something like:

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

Note that I changed "weather" to "total" on the last line because I assumed that's what you intended!

OTHER TIPS

temp_weather should store a list of values. Which means it has to be a list. In your current code, the while loop iterates x times but the temp_weather variable is over written every time. And hence it just stores the last value.

Declare temp_weather as a list like this:

temp_weather = []

Now, change your code as:

while x <= weather:
    y = input("What is the rainfall for day " +str(x)+"? ")
    temp_weather.append(int(y))
    x=x+1

Now, temp_weather will have a list of values. To get the total, you can just use the sum() method:

total = sum(temp_weather)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top