Is_prime: I don't know what I am doing wrong


#1

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

#2

wrong one

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

#3

if x is less then 2, range produces an empty list so the loop won't run

you will need to check if x is less then 2 before the loop

A function ends the moment a return keyword is reached, so your loop ends in its first iteration. That can't be right, for a number to be a prime number, the loop needs to finish running (x mustn't be divisible by all the values for n in range)


#4

Have a look at this thread, not exactly the same as your starting code but very similar.


#5

may be there is indentation error in else statement


#6

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