Python - 识别整数是否为素数?输出同时打印素数和非素数

Python - identifying if integer is a prime or not? Output prints both a prime and not a prime

#Enter an integer
num = int(input("Enter a number: "))

#Prime number is a positive integer that is evenly divisible by 1 and itself
#Zero and one shouldn't be prime numbers

#Use for loop in the range of 2 as the first prime to any integer num
#If else statements: If integer num is divisible by any integer between
#2 and itself the integer num isn't a prime number
#or else the integer is a prime number

if num < 2:
    print(num, "isn't a prime number")

for x in range(2, num):
    if num % x == 0:
        print(num, "isn't a prime number")
        break
else:
    print(num, "is a prime number")

观察-

当我分别输入整数 0 和整数 1 时得到的输出是:

0 isn't a prime number 
0 is a prim number
1 isn't a prime number
1 is a prime number

请记住,这是在 for 循环之前的 if 语句。有了它,整个程序输出每隔一个整数都是正确的。但对于整数 0 和 1 仍然如此:

它输出:

0 is a prime number
1 is a prime number

确认低于2后需要停止:

仅使用以下 一个 ...

如果您正在循环,继续下一次迭代:

if num < 2:
    print(num, "isn't a prime number")
    continue

如果您在一个函数中,并且想要 return 一个值:

if num < 2:
    print(num, "isn't a prime number")
    return False

如果您不是在循环或在函数中,并且想终止程序:

if num < 2:
    print(num, "isn't a prime number")
    sys.exit()

您在检查 num < 2 时没有 return。您可以更改为:

if num < 2:
    print(num, "isn't a prime number")
    return

假设你在函数中。否则你可以使用 else:

if num < 2:
    print(num, "isn't a prime number")
else:
    for x in range(2, num):
        if num % x == 0:
            print(num, "isn't a prime number")
            break
    else:
        print(num, "is a prime number")

您在初始 IF 条件后没有 return 语句或 else 子句。

也只是一个快速提示,无需检查每个整数的模数直到数字。我相信只需要一半的数量。自从我编写素数算法以来已经有一段时间了。