About the is_prime function


#1

here is my codes:
def is_prime(x):
if abs(x)<2:
return False
for i in range(2,x):
if x%i==0:
return False
else:
return True
print range(2,1)

****************************************

I knew this is wrong but idont know how to correct it in a easy way. thx


#2

ops. And the"print " code was my test. just ignore it


#3

This should work

def is_prime(x):                         
    if abs(x) < 2:                          #You forgot that 2 is also a non prime number
        return False
    for i in range(1,x):            
        if x % i == 0:                      # You did i % x instead of x % i                        
            return False
        else:
            return True
        
print is_prime(2)                       #Then afterwards, you need to call your function

#4

I get your point and correct it. thx
But I don't think yours is correct.
-_-


#5

Why is it not correct then? Please leave some more specific info about what's not working, thanks! :smile:


#6

First would be making it so we can read it. Use the </> key above the entry area near the hypertext icon.

Now on to your problem.

Just by asking if x is less than 2 it will encompass all the negatives because let's face it, it is less than 2.

Then as you can see I moved the final return to the first scope so that after everything else complete it always returns True, that is because it is True if everything else fails.

Doing that it works.

New Function

def is_prime(x):
    if x<2:
        return False
    else:
        for i in range(2,x):
            if x%i==0:
                return False
    return True

#7

oops I did an edit, on the "range(2,x)" , and the "if abs()...", sorry for the minor mistakes


#8

THAT code is much more concise than mine!
(Don't know this word is proper)


#9

@learn5704

That is your code, minus the stuff you don't need.


#10

AND may I see your anti_vowel code?
I am not much confident about mine.


#11

This is working and its short code:

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