3

I have simple task to count number, for example:

a = 7
b = 9
result = 0

for _ in (0:100):
     result = a / b
     b += 1

How I can stop the for loop when result is an integer?

Checking if method is_integer() wasn't meet my expectations.

I have to use Python 2.6

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 2
    Try using `while` instead `for` loop – ᴀʀᴍᴀɴ Jan 09 '16 at 11:04
  • @Arman `while` is lowercase – Arc676 Jan 09 '16 at 11:05
  • 1
    I hope yoiu know the above code is not even syntactically valid - the for statement in Python always iterate through sequences - if you want a numeric for loop, the usueal thing to do is to use the built-in `range` function - thus: `for _ in range(0, 100):` is a valid way to do it. – jsbueno Jan 09 '16 at 11:07
  • In Python 2.x, the normal division is constrained to integer results by default - so you probably have problems very soon. You can, on the first line of your program, write the statement `from __future__ import division` so that the result of an integer division can be a float. – jsbueno Jan 09 '16 at 11:09
  • I rolled back your latest edit. On Stack Overflow, you mark a problem as resolved by accepting an answer. If none of the answers is completely satisfying, feel free to post an answer of your own. – tripleee Jan 09 '16 at 12:49

3 Answers3

3

Use % 1. Modular arithmetic returns the remainder, so if you try to divide by 1 and the remainder is 0, it must be an integer.

if result % 1 == 0:
    print "result is an integer!"

OR use the method mentioned in this post or this post:

if result.is_integer():

As mentioned in the comments, you can use:

while result % 1 != 0:

to make the loop repeat until you get an integer.

Community
  • 1
  • 1
Arc676
  • 4,445
  • 3
  • 28
  • 44
2

If you're using python 2.6 you could use:

isinstance(result, (int, long))

to check if your result is an integer.

trantimus
  • 55
  • 6
1

You could use the type method:

if type(a/b) == int:
    break

You could also use the while loop approach as suggested by other answers:

   while type(a/b) != int:
       # your code
deborah-digges
  • 1,165
  • 11
  • 19