How can I exclude negative numbers?

时间:2019-04-16 22:07:59

标签: python list loops

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.

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

答案 2 :(得分: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)

答案 3 :(得分: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)