【问题标题】:How can I create a 'while'-exception loop?如何创建“while”异常循环?
【发布时间】:2018-12-01 21:39:58
【问题描述】:

我正在处理一个需要用户输入的小型编码挑战。应检查此输入是否为数字。我创建了一个“try: ... except ValueError: ...”块,它检查一次输入是否为数字,但不是多次。我希望它基本上可以连续检查。

可以创建一个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: "))

【问题讨论】:

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


    【解决方案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!
    

    我添加标志 boolean 以使其即使输入正确并删除输入也不会重复,除非它会询问 2 次。

    【讨论】:

    • 非常感谢您的回答。它解决了我的问题! :)
    【解决方案2】:

    如果你只按 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
    

    【讨论】:

      猜你喜欢
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 2016-05-13
      • 1970-01-01
      • 2023-02-09
      • 2021-02-20
      • 1970-01-01
      相关资源
      最近更新 更多