[英]when I take 2 as an input here and use else in function it returns non but i remove the else part and use return without indentation it works properly
When I enter 2 as input, i receive None as output. Why does this happen?当我输入 2 作为输入时,我收到的 None 为 output。为什么会这样? My code is:我的代码是:
def prime_number(x):
if x<2:
return False
for i in range(2, x):
if x%i==0:
return '{} is not a prime number'.format(x)
else:
return "Your number is a prime number"
num = int(input("Enter a number to check whether it is prime or not"))
print(prime_number(num))
In your code在你的代码中
for i in range(2, x)
is empty.是空的。 You are asking for a range starting at 2 and INCREASING by 1 until it is greater than 1. This returns an empty list.您要求的范围从 2 开始,递增 1,直到大于 1。这将返回一个空列表。 You need to adjust your code to cater for the unique situation with 2, which falls outside of range(2,x).您需要调整代码以适应 2 超出范围 (2,x) 的独特情况。 An explicit statement that 2 is a prime number is easiest:明确声明 2 是质数是最简单的:
def prime_number(x):
if x<2:
return False
elif x == 2:
return "Your number is a prime number"
else:
for i in range(2, x):
if x % i == 0:
return '{} is not a prime number'.format(x)
else:
return "Your number is a prime number"
num = int(input("Enter a number to check whether it is prime or not"))
print(prime_number(num))
When using the range()
function in a for loop, the loop will iterate from the start value to the end value - 1
.在 for 循环中使用range()
function 时,循环将从开始值迭代到结束value - 1
。 If the end value is 2, then it iterate upto 1.如果最终值为 2,则迭代到 1。
In your case the range is (2,x)
.在您的情况下,范围是(2,x)
。 If the value of the x
becomes 2
then the range is (2, 2)
.如果x
的值变为2
,则范围为(2, 2)
。 It means the starting is from 2
and ending range is 1
.这意味着从2
开始,结束范围是1
。 So there is no iteration .所以没有迭代。 This is why you are getting an output as none .这就是为什么您得到 output 作为none的原因。
This is because the range()
function generates a sequence of numbers up to, but not including, the end value.这是因为range()
function 生成了一个数字序列,但不包括最终值。 If you need to include 2
as the end value, then you need to an increment to the last value as x+1
.如果您需要包含2
作为最终值,则需要将最后一个值递增为x+1
。
For a prime number program you shouldn't add the last value as the number.对于素数程序,您不应将最后一个值添加为数字。 Because a number can be divisible by itself.因为一个数可以被自己整除。 The actual problem is your login in the code.实际问题是您在代码中登录。 You need to add a Flag variable to determine whether a number is prime or not.您需要添加一个Flag变量来确定一个数是否为素数。
num = 2
flag = False
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.