Skip to content
← Back to Community
Prime numbers list in python 3 ?
Profile icon
davidpython3

Hi, I'm working at a project and I need a list of all the prime numbers, well not all but like a function that gives me this list in a given range. (In python 3). Who knows how to do this ?

EDIT : Found it, no problem
I will put here the code if someone needs it -- >
CODE :

primeNumbers = []
for number in range(2, 14):
counter = 0
divisorsList = []
while True:
counter += 1

if counter == number + 1: break if number % counter == 0: divisorsList.append(counter)

if len(divisorsList) == 2:
primeNumbers.append(number)

print("divisorsList (test) -- {0}".format(divisorsList))
print("prime numbers in range(2, 14) -- {0}".format(primeNumbers))

#You can make a function and at the range put some parameters called x, y and the range will be range(x, y) and global the prime numbers so that you can get the list.

Voters
Profile icon
Sarah-KarenKare
Profile icon
SeamusDonahue
Profile icon
davidpython3
Comments
hotnewtop
Profile icon
BrightSideSide
Profile icon
GulliverM

!WARNING, not tested!

prime_nums = [] w = [] for i in range(100): # change 100 to whatever you want if not i in w: w.append([x*i for x in range(1, 100)]) # set 100 to the same number above prime_nums.append(i)
Profile icon
SeamusDonahue

if you question has not been answered yet:

try: int(number**0.5) prime = True except: prime = False

so basically that detects if the square root of number is a whole number.

Profile icon
GulliverM

@SeamusDonahue does that actually work?

Profile icon
SeamusDonahue

reading this function again not really because int would truncate it: here is a working version

if int(n**0.5) == n**0.5: prime = False #if it was prime, the result should be float else: prime = True

in a function return true or false, but that should function
just so you know ** is exponent, so **0.5 is square root
@Stan085

Profile icon
SeamusDonahue

to get a list, append the result to it depending on what you want (list of primes: listname.append(n), list of booleans: listname.append(True/False))

Profile icon
amasad

@davidpython3 a great place to ask questions would be our discord server 😊 https://discord.gg/gr2fPQ

Profile icon
davidpython3

@amasad Ok, thx for that :D