提示用户,直到他们给出的数字不是字符串,而且数字大于输入的前一个数字

时间:2018-01-08 00:07:04

标签: python-3.6

我正在制作一个程序,用户需要输入2个数字(负数或正数),第二个数字必须比第一个数字大至少2个。有没有办法确保用户输入。我已经拥有它所以只有一个数字,但有一种方法可以同时做两个。这是我的代码:

while True:
    try:
        lowest_num = int(input("What would you like the lowest possible number to be?"))
        break
    except ValueError:
        print("Please only enter a number.  Try again... ")

while True:
    try:
        highest_num = int(input("What would you like the highest possible number to be?"))
        break
    except ValueError:
        print("Please only enter a number and a number that is bigger than the previous number.  Try again...")

我需要这样的东西与“highest_num循环”在同一个循环中:

while highest_num <= (lowest_num + 1):
    highest_num = input("Please only enter a number and a number that is bigger than the previous number.")

有办法吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

好的,我在while内添加了一个新的try循环,如下所示:

while True:
    try:
        highest_num = int(input("What would you like the highest possible number to be?"))
        while highest_num <= (lowest_num + 1):
            highest_num = int(input("Please only enter a number and a number that is bigger than the previous number."))
        break
    except ValueError:
        print("Please only enter a number and a number that is bigger than the previous number.  Try again...")

我很确定这有效!