#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
请记住这是if
循环之前的for
语句。有了它,整个程序输出每隔一个正确的整数。但仍然是整数0和1:
输出:
0 is a prime number
1 is a prime number
答案 0 :(得分:2)
检查num < 2
时,您不会返回。你可以改为:
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")
答案 1 :(得分:0)
一旦确认它低于2
:
仅使用以下一个 ...
如果您正在循环,则继续下一次迭代:
if num < 2:
print(num, "isn't a prime number")
continue
如果你在一个函数中,并想要返回一个值:
if num < 2:
print(num, "isn't a prime number")
return False
如果您没有循环或在函数中,并且想要终止该程序:
if num < 2:
print(num, "isn't a prime number")
sys.exit()
答案 2 :(得分:0)
在初始IF条件之后,您没有return语句或else子句。
也只是一个快速提示,无需检查每个整数的模数。我相信只有一半的数字是必要的。我编程了一个素数算法已经有一段时间了。