Am trying to write a piece of python code that calculate and print 1000 prime number from 2
however i only got 1999 as the last element in my result. I know there a lot of questions like this asked before but I wanna know why is my code is not working.
btw: how do i declare a boolean value in python? cant find a clue even googled···sad
mylist=[2]
num=1
count=0
while count<1000:
if num>1:
add=1
for i in mylist:
if num%i==0:
add=0
break
if add==1:
mylist=mylist+[num]
num=num+2
count=count+1
print mylist
Your loop should read
while len(mylist) < 1000:, and remove all references tocount. Either that, or you should only incrementcountevery time you add a prime to the list.Also, you don’t ‘declare’ values in Python. You simply assign a value of the desired type to a variable, and poof, you have a variable of that type. In this case,
TrueandFalseare boolean values and you can assign them to variables.Here is my version in idiomatic (i.e. written the way an experienced Python programmer might write it) Python:
If you want to write it in even terser and faster Python, do this: