Function is_prime - Error
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 Question
01:24 Accepted answer (Score 11)
01:51 Answer 2 (Score 4)
02:29 Answer 3 (Score 0)
02:41 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 Question
01:24 Accepted answer (Score 11)
01:51 Answer 2 (Score 4)
02:29 Answer 3 (Score 0)
02:41 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 theforloop never runs.- Therefore,
lstis still[]after the loop. - Therefore,
'False' in lstisFalse - Therefore,
return Trueis 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