tags:

views:

94

answers:

2

Hello, I can't understand one thing with logic in python. Here is the code:

maxCounter = 1500
localCounter = 0

while True:
   print str(localCounter) + ' >= ' + str(maxCounter)
   print localCounter >= maxCounter

   if localCounter >= maxCounter:
      break

   localCounter += 30

And the result output:

...
1440 >= 1500
False
1470 >= 1500
False
1500 >= 1500
False
1530 >= 1500
False
1560 >= 1500
False
...

And I have infinity cycle there. Why?


topPos = someClass.get_element_pos('element')
scrolledHeight = 0

while True:
    print str(scrolledHeight) + ' >= ' + str(topPos)
    print scrolledHeight >= topPos
    if scrolledHeight >= topPos:
        print 'break'
        break

    someClass.run_javascript("window.scrollBy(0, 30)")
    scrolledHeight += 30
    print scrolledHeight

    time.sleep(0.1)
+4  A: 

To fix your code try this:

topPos = int(someClass.get_element_pos('element'))

Why?

When I copy and paste your original code I get this:

...
1440 >= 1500
False
1470 >= 1500
False
1500 >= 1500
True

One small change that I can find to make to your code that reproduces the behaviour you are seeing is to change the first line to this:

maxCounter = '1500'  # string instead of integer

After making this change I can also see the output you get:

1410 >= 1500
False
1440 >= 1500
False
1470 >= 1500
False
1500 >= 1500
False
1530 >= 1500
False
etc..
Mark Byers
Yeah, I made such stupid error =( That was a string. Thank you.
Ockonal
Luckily in Python 3.x this source of errors has been fixed. Comparing a string to an integer will give an error: `TypeError: unorderable types: str() > int()`
Mark Byers
+1  A: 

The problem seems to be at this line:

topPos = someClass.get_element_pos('element')

This is likely to assign a string to topPos, instead of a numeric variable. You need to convert this string to a numeric variable so you can do a numeric comparison against it.

topPos = int(someClass.get_element_pos('element'))

Otherwise, e.g. in CPython implementation of v2.7, any int is always going to compare less than any string.

Related questions

polygenelubricants
Yeah, you are right. Sorry, the another answer was posted earlier then youth.
Ockonal