0

I have to get the user to input an integer, but it cannot be negative. However, whenever I test the program, if enter a negative number, it doesn't allow it. If I enter a negative number a second time, it will allow it. I know why, but I don't know what alternative I can use. Here's how it prints:

What would you like x to be? -5
Sorry, the number of juveniles must be positive. Please try again.
What would you like x to be? -5
What would you like y to be? -9
Sorry, the number of adults must be positive. Please try again.
What would you like y to be? -9
What would you like z to be? -10
Sorry, the number of seniles must be positive. Please try again. 
What would you like z to be? -10

This is my code:

x = int(input("What would you like x to be? "))
if x<0:
    print("Sorry, x must be positive. Please try again.")
    x = int(input("What would you like x to be? "))
y = int(input("What would you like y to be? "))
if y<0:
    print("Sorry, y must be positive. Please try again.")
    y = int(input("What would you like y to be? "))
z = int(input("What would you like z to be? "))
if z<0:
    print("Sorry, z must be positive. Please try again. ")
    z = int(input("What would you like z to be? "))

I've looked all around the place but cannot find a suitable alternative. Please help.

2 Answers2

1

Try something on these lines

while(true):
    x = int(input("What would you like x to be? "))
    if(x > 0):
        break;
Bernardo Meurer
  • 2,295
  • 5
  • 31
  • 52
0

if will only check once. Just replace your if statements by while:

x = int(input("What would you like x to be? "))
while x<0:
    print("Sorry, x must be positive. Please try again.")
    x = int(input("What would you like x to be? "))
y = int(input("What would you like y to be? "))
while y<0:
    print("Sorry, y must be positive. Please try again.")
    y = int(input("What would you like y to be? "))
z = int(input("What would you like z to be? "))
while z<0:
    print("Sorry, z must be positive. Please try again. ")
    z = int(input("What would you like z to be? "))
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55