+ 1

Problems with functions - Why is the output not only a List of Prime numbers?

def isPrime(n): if n <= 1: exit for i in range(2, n): if n %i == 0: exit print(n) return for x in range(11): isPrime(x) Why is the output not only a List of Prime numbers? Can someone explain my fault? Thank you, guys!

19th Mar 2018, 11:08 PM
Peter
6 Antworten
+ 3
You should not use exit. You should use return
19th Mar 2018, 11:35 PM
cyk
cyk - avatar
+ 3
No problem! :) And if you do what Ariela said it works as well and it goes through the loop about half as many times... Take a look at this code. And please, do upvote the answers if they help you. https://code.sololearn.com/cqkftOPwy3HI/?ref=app
19th Mar 2018, 11:38 PM
cyk
cyk - avatar
+ 2
First of all, I’m pretty sure you can do n/2 to optimize it Other than it should work
19th Mar 2018, 11:18 PM
Ariela
Ariela - avatar
+ 2
Oh I meant n/2+1 because range is exclusive for the second value
19th Mar 2018, 11:19 PM
Ariela
Ariela - avatar
+ 1
Thx for the improvement, but if i run the Code, i get the range(11) aus a result
19th Mar 2018, 11:24 PM
Peter
+ 1
Thanks
19th Mar 2018, 11:36 PM
Peter