drewteriyaki - 2 months ago 6

Python Question

So I have this code and it is supposed to print out a tuple with all the prime numbers in it. But instead, it's just printing out a empty tuple...

Can anyone tell me why?

I also MUST USE A TUPLE.

`def isPrime(number):`

for i in range(2,int(number**(0.5))+1):

if number % i == 0:

return False

else:

return True

def allPrimes(number):

tup=()

for i in range(1,number):

if isPrime(i) == True:

tup += (i,)

print(tup)

allPrimes(26)

Here is the correct code

`def isPrime(number):`

if number < 2:

return False

for i in range(2, int(number ** (0.5)) + 1):

if number % i == 0:

return False

return True

def allPrimes(number):

tup=()

for i in range(1,number):

if isPrime(i) == True:

tup += (i,)

print(tup)

allPrimes(26)

out[1]: (2, 3, 5, 7, 11, 13, 17, 19, 23)

Answer

Your `isPrime()`

function starts at 1. Every integer is evenly divisible by 1, so it always returns `False`

. Start at 2 instead.

```
def isPrime(number):
if number < 2:
return False
for i in range(2, int(number ** (0.5)) + 1):
if number % i == 0:
return False
return True
```

Also, your allPrimes should probably use a list rather than a tuple, and you could use just `isPrime(i)`

instead of `isPrime(i) == True`

, but it'll work the way it is.

Source (Stackoverflow)

Comments