David
David

Reputation: 69

Function to check if number is a prime number

def is_prime(n):
   
    if n >= 2:
        for i in range(2, n):
            if not (n % i):
                return False
    else:
        return False
    return True

I was trying to make a code that would dheck if a number is a prime numeber. I found this code on the internet and it works great. However, I am relatively new to coding so I was wondering if someone could explain the final 2 lines for me. Why do you return True after return False ?

Upvotes: 2

Views: 1440

Answers (3)

Melvin Abraham
Melvin Abraham

Reputation: 3036

If you look at the statement if n >= 2, you will notice that it does all the main computation for any number which is greater than 2. What happens if the number n passed is less than 2? Well, the else statement is called. So, when n is either 0 or 1, you know it's not a prime number. Thus, return False is executed which tells that the number is not a prime number.

Coming to the other line. When all the computation is done and return False has not executed even once, the interpreter arrives at the last line of the function and executes return True which tells that the number is a prime number.

Examples


  • When n = 6

    Statement n >= 2 evaluates to True, so, the for-loop is executed. When the value of loop variable i is 2, the line if not (n % i) evaluates to True and then return False is executed which tells that n is not a prime number.

  • When n = 5

    Statement n >= 2 evaluates to True, so, the for-loop is executed. None of the values of i are divisible with n, hence, no return statement is executed. Finally, the last line of the function is reached and return True is executed which tells that n is a prime number.

  • When n = 0

    Statement n >= 2 evaluates to False. Thus, the return False statement under else statement is executed which tells that n is not a prime number.

Upvotes: 1

Red
Red

Reputation: 27567

return True tells python to return a boolean value of True, and return False tells python to return a boolean value of False. If calling the function with a certain number gives you True, that certain number is a prime number. Else, it is not a prime number.

Upvotes: 2

wakey
wakey

Reputation: 2409

The return False is inside the else block, whereas the return True is only run if the if succeeds.

Another way of writing the same program

def is_prime(n):
   
    if n >= 2:
        for i in range(2, n):
            if not (n % i):
                return False
        return True  # Return True here, instead of at the end
    else:
        return False

This does the exact same thing, I just moved the return True statement inside the first if block.

Upvotes: 2

Related Questions