请在进行空运行时澄清我的错误

时间:2018-09-06 13:39:17

标签: python

以下代码都是正确的,但我对此表示怀疑。在进行空运行时,我发现应该将2表示为非质数。请有人说明代码的运行情况。

num = 4
if num > 1:
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")

else:
   print(num,"is not a prime number")

1 个答案:

答案 0 :(得分:0)

2是素数,但是您的代码会将2显示为不是素数

这里是解决方法:

num = 4
if num > 2:
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")

elif num = 2
    print(num, "is a prime number")

else:
   print(num,"is not a prime number")