Andrew Lastrapes
Andrew Lastrapes

Reputation: 187

Python: Only return integers

I want to find the prime factors for 13195.

for num in range(1,13196):
    x = 13195/num 

I want x to only store integers. I've tried is.integer and but keep getting syntax errors.

Upvotes: 2

Views: 2759

Answers (2)

Taku
Taku

Reputation: 33744

I've tried is.integer and but keep getting syntax errors.

The method for checking if a float is an integer is called is_integer() not is.integer(), so alternatively, you can do this:

for num in range(1,13196):
    x = 13195/num 
    if x.is_integer():
        print(num)

Or by adding the brackets:

for num in range(1,13196):
    if (13195/num).is_integer():
        print(num)

Upvotes: 3

Kewl
Kewl

Reputation: 3417

You could use the modulo operator to check if a number is divided evenly, and only set x equal to it then. E.g.:

for num in range(1,13196):
    if 13195 % num == 0:
        x = int(13195/num)
        print(x)

which gives:

13195
2639
1885
1015
455
377
203
145
91
65
35
29
13
7
5
1

Upvotes: 4

Related Questions