如何在python中允许输入超过一定数量

时间:2016-03-13 19:36:47

标签: python python-3.x input printing integer

我必须让用户输入一个整数,但它不能是负数。但是,每当我测试程序时,如果输入一个负数,它就不允许它。如果我第二次输入负数,它将允许它。我知道为什么,但我不知道我可以用什么替代品。以下是它的打印方式:

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

这是我的代码:

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? "))

我看了看周围的地方,但找不到合适的替代品。请帮忙。

2 个答案:

答案 0 :(得分:1)

在这些方面尝试一些事情

while(true):
    x = int(input("What would you like x to be? "))
    if(x > 0):
        break;

答案 1 :(得分:0)

if只会检查一次。只需将if语句替换为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? "))