awsomeguy
awsomeguy

Reputation: 191

Why is there a TypeError

Why does this:

def p3(x):
        primes = [2]
        for a in range(3, x, 2):
            sqrt = a ** 0.5
            for b in range(3, sqrt, 2):
                if a % b == 0:
                    break
            if a % b != 0:
                primes.append(a)
        return primes
    print(p3(19))

return this:

TypeError: 'float' object cannot be interpreted as an integer, line 5

What does it mean and how do I correct it?
Thanks in advance,
LewisC

Upvotes: 0

Views: 7490

Answers (2)

Pavel Anossov
Pavel Anossov

Reputation: 62868

Because sqrt is a float and range expects strictly integers.

You probably want this:

for b in range(3, int(sqrt) + 1, 2):

Upvotes: 6

NPE
NPE

Reputation: 500157

sqrt is of type float and therefore can't be used with range():

>>> range(1, 2.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

To fix, convert it to integer:

sqrt = int(a ** 0.5)

Upvotes: 0

Related Questions