Python 15.6 Is_Prime


#1

Hello Friends,I am once again seeking your help because I am stuck at
https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096# Following is my code

def is_prime(x):
    if x<=1:
        return False
    elif x==2 or x==3:
        return True
    else:
        for n in range (2,x-1):
            if x%n==0:
                return False
            else:
                return True
                
print is_prime(1)
print is_prime(2)
print is_prime(3)
print is_prime(4)

Also,Does any body thinks my "elif": statement is cheating.


#2

Are 2 and 3 really special cases?
In each iteration of your loop, you either exit the function, or you exit the function. In other words, there will never be a second iteration.


#3

Please, can you tell me how to fix it ?


#4

Refer to how you do it manually. If you don't understand what the code is doing then you can read more about whatever you don't understand what it does, and you can also use print statements to see what order it does things in


#5

I solved the problem .Just "untab" the final else statement only once


#6

i think this code is more correct:

def is_prime(x):
    count = 0
    for i in range(1, x+1):
        if x % i != 0:
            continue
        else:
            count += 1
    if count == 2:
        return(True)
    else:
        return(False)

#7

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