When I enter 2 as input, i receive None as output. Why does this happen? 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))
CodePudding user response:
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. You need to adjust your code to cater for the unique situation with 2, which falls outside of range(2,x). An explicit statement that 2 is a prime number is easiest:
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))
CodePudding user response:
When using the range()
function in a for loop, the loop will iterate from the start value to the end value - 1
. If the end value is 2, then it iterate upto 1.
In your case the range is (2,x)
. If the value of the x
becomes 2
then the range is (2, 2)
. It means the starting is from 2
and ending range is 1
. So there is no iteration. This is why you are getting an output as none.
This is because the range()
function generates a sequence of numbers up to, but not including, the end value. If you need to include 2
as the end value, then you need to an increment to the last value as 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.
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")