2

I am not sure how to prevent a negative number from affecting the final calculations.

I don't know what else to try.

for month in months:
    rainfall_answer = int(input("What was the rainfall in {}? ".format(month)))
    if rainfall_answer < 0:
        print("Input must be positive.")
        rainfall_answer = int(input("What was the rainfall in {}? ".format(month)))
    elif rainfall_answer > 0:
        rainfall.append(rainfall_answer)

I expect the invalid input to not be included in the final results.

coco
  • 79
  • 3
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Peter Wood Apr 16 '19 at 22:39

4 Answers4

1

If I understand you correctly, you can use a while loop to repeatedly prompt the user until the input is non-negative:

for month in months:
    rainfall_answer = int(input("What was the rainfall in {}? ".format(month)))
    while rainfall_answer < 0:
        print("Input must be positive.")
        rainfall_answer = int(input("What was the rainfall in {}? ".format(month)))

    rainfall.append(rainfall_answer)
iz_
  • 15,923
  • 3
  • 25
  • 40
1

You're almost there, one trick you can use is to set rainfall_answer to a negative (invalid) value, then you can repeat input reading until you have a positive value in rainfall_answer:

for month in months:
    rainfall_answer = -1
    while rainfall_answer < 0:
        rainfall_answer = int(input("What was the rainfall in {}? ".format(month)))
    rainfall.append(rainfall_answer)
cglacet
  • 8,873
  • 4
  • 45
  • 60
1

You can make use of while loop to loop over the input and also you need to use a try except blocks to handle and raise exception in this case excluding negative numbers

for month in months:
  while True:
    try:
        rainfall_answer = int(input("What was the rainfall in {}? ".format(month)))
        if rainfall_answer < 0:
            raise ValueError
        break
    except ValueError:
        print ("Input must be positive")
rainfall.append(rainfall_answer)
cglacet
  • 8,873
  • 4
  • 45
  • 60
WaLid LamRaoui
  • 2,305
  • 2
  • 15
  • 33
0

You need to loop over the input.

for month in months:
    while True:
        rainfall_answer = int(input("What was the rainfall in {}? ".format(month)))
        if rainfall_answer >= 0:
            break  # exit while loop because you got valid input
        else:
            print('Input must be positive')
    rainfall.append(rainfall_answer)     
Tom Lubenow
  • 1,109
  • 7
  • 15