如何创建“ while”例外循环?

时间:2018-12-01 21:39:58

标签: python python-3.x while-loop exception-handling

我正在研究一个小的编码挑战,需要用户输入。此输入应检查为数字。我创建了一个“ try:... ValueValue:...除外”块,该块检查一次输入是否为数字,但不是多次。我希望它基本上可以连续进行检查。

可以创建一个while例外循环吗?

我的代码如下:

try:
    uinput = int(input("Please enter a number: "))

    while uinput <= 0:
        uinput = int(input("Number is negative. Please try again: "))
    else:
        for i in range(2, uinput):
            if (uinput % i == 0):
                print("Your number is a composite number with more than
                       one divisors other than itself and one.")
                break
            else:
                print(uinput, "is a prime number!")
                break

except ValueError:
    uinput = int(input("You entered not a digit. Please try again: "))

2 个答案:

答案 0 :(得分:1)

flag = True
while flag:
    try:
        uinput = int(input("Please enter a number: "))

        while uinput <= 0:
            uinput = int(input("Number is negative. Please try again: "))
        else:
            flag=False
            for i in range(2, uinput):
                if (uinput % i == 0):
                    print("Your number is a composite number with more than one divisors other than itself and one.")
                    break
                else:
                    print(uinput, "is a prime number!")
                    break

    except ValueError:
        print('Wrong input')

输出:

(python37) C:\Users\Documents>py test.py
Please enter a number: qwqe
Wrong input
Please enter a number: -123
Number is negative. Please try again: 123
123 is a prime number!

我添加了标志布尔值,即使输入正确也不会重复它,并且删除了输入,因为它会询问2次。

答案 1 :(得分:0)

如果仅按Enter,则循环终止:

while True:

    uinput = input("Please enter a number: ")
    if uinput.strip()=="":
        break
    try:
        uinput=int(uinput)    
    except:
        print("You entered not a digit. Please try again")
        continue

    if uinput<=0:
        print("Not a positive number. Please try again")
        continue

    for i in range(2, uinput):
            pass; # put your code here