Psyduck
Psyduck

Reputation: 667

float' object cannot be interpreted as an integer

I have code:

  a = int(input("Type a integer:"))
    temp = []
    while a != 1:
  --->   for i in range(2, a):
            if a % i == 0:
                temp.append(i)
                a = a / i
                break
    print(temp)

I typed 60 and then it gives the error: TypeError: 'float' object cannot be interpreted as an integer.

However, I checked:

a = int(input("Type a integer"))
type(a)

It shows type of a is int.

If so, where is the float type comes from?

Upvotes: 2

Views: 19696

Answers (3)

evanklicker
evanklicker

Reputation: 121

When you divide a by i, it becomes a decimal number after so many iterations. If you started with 60, then the operations would follow like this:

a = 60 / 2     (=30)
a = 30 / 3     (=10)
a = 10 / 4     (=2.5)

Now, we can see that a is trying to be a float when you told it to be an integer.

Upvotes: 4

Martin the noob
Martin the noob

Reputation: 11

The float comes from using float division a/i. To get an int use integer division a//i

Upvotes: 1

ZAhmed
ZAhmed

Reputation: 1290

When you divide it by a number , it become a float , you can return it to integer by :

a = int(a)

after

a = a/i

Or :

 a = a//i

Upvotes: 1

Related Questions