It only returns "None"


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096
Please, can someone tell me what's wrong with this code?

def is_prime(x):
  
    if x>2:    
        for n in range(2,x):
            if x%n==0:
                break
                return False
            else:
                return True
               
    elif x==2:
        return True
    else:
        return False


#2

well, for x=4 the first number tested by the loop is n=2:

4 % 2 == 0

which is true, so the loop breaks (break keyword), then your program is finished running

why would you use the break keyword? return will end the function, if a return keyword is reached in a loop, the function still needs to end so the loop breaks (in manner of speaking)


#3

def is_prime(x):

if x>2:    
    for n in range(2,x):
        if x%n==0:
            break

As @stetim94 stated - there is no need for this break keyword

            return False
        else:

also your "else" should be out-dented, because this way it stops the "for" loop and it does not check all numbers smaller than "x"

            return True

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

Also use some space between the operands - ex. "x % n == 0" instead of "x%n==0".


#4

not true

i know, i help in steps

I did very briefly cover this problem:

i would have gone more in depth if that was needed


#5

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


#6

#7

@microjumper11250 did you resolve the issue? Topics auto-close to prevent hijacking, but did you have enough help?


#8

As it can be found here: https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces:

  • Always surround these binary operators with a single space on either side: assignment ( = ), augmented assignment ( += , -= etc.), comparisons ( == , < , > , != , <> , <= , >= , in , not in , is , is not ), Booleans ( and , or , not ).

Yes:

i = i + 1

No:

i=i+1


#9