如果数字为5609,则输出为“此数字为质数”,即使我知道它不是质数也是如此。

如果数字为5609,则输出为“此数字为质数”,即使我知道它不是质数也是如此。为什么我得到那个输出? 与其他几个休闲数字一起工作。

    number = int(input())
    if number <= 1:
        print("This number is not prime")

    for i in range(2, number):
        if number % i == 0:
            print("This number is not prime")
            break
        print("This number is prime")
        break
评论
  • et_et
    et_et 回复

    You need to check all the possible factors before declaring number to be prime; you do so as soon as the first value of i (2) does not divide it.

    The quickest fix is to move the last print statement out of the body of the loop to an else block following the loop.

    number = int(input())
    if number <= 1:
        print("This number is not prime")
    
    for i in range(2, number):
        if number % i == 0:
            print("This number is not prime")
            break
    else:
        print("This number is prime")
    

    The else block is only executed if the loop exits "naturally", by exhausting its iterators, rather than by a break statement.

  • sut
    sut 回复

    这仅适用于偶数的非素数。这应该更好地工作(for循环的最后打印出)

        number = int(input())
        prime = True
        if number <= 1:
            print("This number is not prime")
    
        for i in range(2, number):
            if number % i == 0:
                prime = False
                print("This number is not prime")
                break
        # Print this when all numbers are looped.
        if Prime:
            print("This number is prime")