Function is_prime - Error - python

This is a question from codeacademy.com, where I am learning Python.
So what I want is to define a function that checks if a number is prime.
If it is, return True.
If it isn't, return False.
Here is my code:
def is_prime(x):
lst = [] # empty list to put strings 'False' and 'True'
for i in range(2,x): # starting at 2 and not including x (number 1 is a divisor of all numbers
if x <= 2: # [1] see bellow the explanation
lst.append('False')
break
elif x % i == 0: # if x is divisible by i(number between 2 and not including x)
lst.append('False')
break # break, because we already know x is not prime
elif x % i > 0:
lst.append('True') # x is not divisible by i
if 'False' in lst:
return False # x is not prime - return False
else:
return True # 'True' is in lst, so x is prime - return True
print is_prime(-2) # [2] I get an error here. See below
[1] - I made this condition because in codeacademy it says:
"Hint
Remember: all numbers less than 2 are not prime numbers!"
[2] - When I run, for example, 'print is_prime(11)' or 'is_prime(6)' it works ok. So I submit the answer, but codeacademy doesn't accept it. It says:
"Your function fails on is_prime(-2). It returns True when it should return False."

Let's see what happens when you enter -2:
range(2,-2) is empty, so the for loop never runs.
Therefore, lst is still [] after the loop.
Therefore, 'False' in lst is False
Therefore, return True is executed.

When x is -2, range(2, x) will produce an empty list.
print range(2, -2) # will print []
So, the loop and the if conditions inside the loop will not be executed. The last if condition will be checked and no 'False' is in the lst. So, it returns True.
You can write the same program like this
def is_prime(x):
if x < 2:
return False
prime_flag = True
for i in range(2,x):
if x % i == 0:
prime_flag = False
break
return prime_flag
print is_prime(-2)

def is_prime(x):
if x < 2:
return False
for n in range(2, (x)-1):
if x % n == 0:
return False
return True

Related

Check prime number

def isPrime(n):
if n>1:
for i in range(2,n):
if (n % i==0):
return False
else:
return True
else:
return False
This code worked in most cases, but when input n=133, it returned True as output. Please show me the error.
Please note that your code could return True in the first iteration of the loop, you need to check for the other values.
Let's see how your loop works.
For value such as 3 your loop will have n%i check i.e. 3%2 which won't satisfy the condition. So it will return true.
But for value such as 9. Loop will check 9%2=0 which again doesn't satisfy the condition and returns True.
So use something like.
def isPrime(n):
if n>1:
for i in range(2,n):
if (n % i==0):
return False
else:
x=False
return x;
else:
return False
So I ran this and it seems this function will return True for any odd number because it returns false on the first iteration, which is checking if it's divisible by 2. Overall, your function is pretty much wrong, here is how I would approach it.
def isPrime(n):
div = True
for i in range(2,int(n**0.5)):
if n%i==0:
div = False
break
return div
Here what I did was I only checked prime factors upto the square root of the number (because if a number has a prime factor greater than its square root(but not the number itself), it must also have a prime factor less than its square root, so we do not need to check further), and I exited from the loop whenever even once it was divisible by something. I checked and it's working correctly.
The problem with your loop is that when you are iterating through the for loop, it always returning either True or False. To prevent that, what you should create a counter which changes its value accordingly.
def PrimeChecker(n):
if n < 1:
return f'{n} is less than 1. So, not prime' # You can add this if you
# want.
else:
for i in range(2, n): # The main loop
counter = True # The counter
if n % i == 0: # If it becomes divisible....
counter = False # Counter becomes false.
break # Break out of loop
return counter # Return False or True
Hope that helped :)
Most efficient Primechecker program :)
from math import sqrt
def checkprime(x):
if x > 2 and x % 2 == 0:
return False
elif x < 2:
return False
else:
for i in range(2, int(sqrt(x)) + 1):
if x % i == 0:
return False
return True
return False

Why is my prime number function not working?

I am new to programming and I face an issue while trying to write a program in finding out prime number. Here is my code:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x-1):
if x % n == 0:
return False
else:
return True
I received an error stating "Your function fails on is_prime(3). It returns None when it should return True."
Can someone please explain the flaw in this code?
Thank you!
range() has an exclusive upper bound, so it's trying to get the range between 2 and 2 (3 - 1), which is no elements. Since you can't iterate over nothing, the for loop never runs, so None is returned (this is the default return type of a function if none is specified).
The solution to your immediate problem would be to use range(2, x) rather than range(2, x - 1). You'll find that you'll have problems at x > 3 though because as #khelwood said, you're returning True or False immediately after checking the first value. Instead, only return True after checking all values in the range.
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x): # range function will iterate till x-1
if x % n == 0:
return False
# return true only at the end after making sure it is not divisible by any number in the middle
return True

Codecademy Python "is_prime" exercise in "Practice Makes Perfect"-Is it really iterating?

I've been plugging away on the Codecademy python course and I had a solution that worked. However, during the verification process, I added an extra bit of code that would print the current state the for loop is in. When I execute the code, however, it seems to go through one iteration before quitting, which I know is not the case. The following is my code:
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
if x == 3:
return True
else:
for n in range(2,x-1):
if x % n == 0:
print "Current value is %d." %n
return False
return True
How can I make it print a value each "n" value when the number is going through the loop?
Your issue is that you are only printing when x % n == 0 , and then right away you are returning 'False' , hence its only printing once.
You need to move the print statement to just below for loop , something like -
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
if x == 3:
return True
else:
for n in range(2,x-1):
print "Current value is %d." %n
if x % n == 0:
return False
return True
Try this one. I'm using Fermat's little theorem :
def is_prime(x):
if x > 1 and ((2)**x-(2))%x == 0:
return True
return False
def is_prime(x):
if x < 2:
return False
else:
for n in range(2,x - 1):
if x % n == 0:
return False
return True

Python prime checker faulty with 25?

So I'm relatively new to Python and trying to define a function which will check to see if a number is prime or not. The code is as follows:
def prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(3, int((x**0.5)+1)):
if x % i == 0:
return False
else:
return True
This seems to work for most values however it fails on certain values such as 25, can anyone help to explain to me why? Thanks!
return leaves your function once it is reached. Let's look at the case of 25.
Is x<2 no, so continue.
Is it x==2 no, so continue.
Is x divisible by i(=3)? No, so go to the else clause, return True leave the function.
See the issue?
To put it another way, for sufficiently large x, your function is equivalent to:
def prime_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
if x % 3 == 0:
return False
else:
return True
It's the
else:
clause, the first i it checks will make it return true.
Instead, write
else:
for i in range(3, int((x**0.5)+1)):
if x % i == 0:
return False
return True
EDIT:
And as #mata points out, you actually need to start at 2, so it should be for i in range(2, int((x**0.5)+1)):

Function that checks primality correction?

Function that checks if input is prime.
I know it has been covered many times here, but my code for some reason gives me True for x=32 and I cant figure out why
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for i in range(3,x): #Ignore sqrt(x) improvement
if x%i == 0:
return False
else :
return True
for i in range(3,x):
This first goes with the number 3. As 32 % 3 != 0, it returns True. Then the function breaks because it has returned a value.
Consider putting return True after the for-loop:
for i in range(3,x): #Ignore sqrt(x) improvement
if x % i == 0:
return False
return True
Now if a number is divisible, it will immediately break and return False. But if no numbers go into 32, the for-loop will finish, and it will return True.
Also, if you are using python 2.x, it will be faster to use xrange(), as that returns a generator :).

Categories

Resources