Is-prime: v confused :-//


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096


I keep getting this error message but think I have is_prime defined on line 3.

Oops, try again.
Did you create a function called is_prime? Your code threw a "global name 'is_prime' is not defined" error.


I expect the first if clause to check if the number entered is 2 or less than 2. The second to check if number entered is 3. And the else to work with all numbers above 3.


n = raw_input('Insert your number!')

def is_prime(x):
    if x < 2:
        return False
    elif x == 3:
        return True
    else:
        for num in range(3,(x-1)):
            if x\num == 0:
                return False
            else:
                return True

Any help would be greatly appreciated. Until now I was trundling along nicely but I've been stuck here a few days now.

Philip


#2

You can set the lower limit of the range to 2. Even with the upper limit being x, the upper bound of the range is one less than that, so x - 1 which will prevent 2 from entering the loop. Have it drop to the very bottom and return True.

The first line inside your function is excluding all values less than 2 and returning False. That line is correct. The elif and the else are not needed. Just go straight into the loop.

Inside the loop, the if condition you have is incorrect. Use the modulo operator, % so you can test the remainder. The if should have no else.

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

The 2 will drop to the bottom, as will any values for x that are not divisible.


#3

Thank you for your assistance. I also appreciate how you explained what was going on in a simple fashion but did not give me the answer completely.

Mucho Appreciado Amigo :slight_smile:


#4

try this one !! it worked

def is_prime(x):
flag=0
if x>=2:
if x==2:
return True
if x==3:
return True

    for n in range(2,x/2+1):
        if x%n==0:
            flag=1
    if flag==0:
        return True
    else:
        return False
else:
    return False

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.