The Python Oracle

Function is_prime - Error

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5

--

Chapters
00:00 Function Is_prime - Error
01:08 Accepted Answer Score 11
01:30 Answer 2 Score 4
01:56 Answer 3 Score 0
02:01 Thank you

--

Full question
https://stackoverflow.com/questions/2072...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #math #numbers #primes

#avk47



ACCEPTED ANSWER

Score 11


Let's see what happens when you enter -2:

  • range(2,-2) is empty, so the for loop never runs.
  • Therefore, lst is still [] after the loop.
  • Therefore, 'False' in lst is False
  • Therefore, return True is executed.



ANSWER 2

Score 4


When x is -2, range(2, x) will produce an empty list.

print range(2, -2) # will print []

So, the loop and the if conditions inside the loop will not be executed. The last if condition will be checked and no 'False' is in the lst. So, it returns True.

You can write the same program like this

def is_prime(x):
    if x < 2:
        return False
    prime_flag = True
    for i in range(2,x):
        if x % i == 0:
            prime_flag = False
            break
    return prime_flag

print is_prime(-2)



ANSWER 3

Score 0


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