0

Just wondering if someone can help me out with a small issue. The while condition works fine when I compare startNum with a constant (startNum < 11) but goes to infinite loop when I compare with endNum. I am curious to understand what am I doing wrong here?

Code Snippet below

startNum = 1
endNum = raw_input('please enter the end number')
def main():

        print startNum
        print endNum
        sumNatural()
        print listNumBoth
        print listNumThree
        print listNumFive




def sumNatural():

    global startNum
    global endNum
    print startNum
    print endNum

    while startNum < endNum:
        listNumThree=[]

        listNumBoth=[]
        listNumFive=[]
        #startNum=1
        #endNum=raw_input('please enter the end number')
        startNum = startNum+1
        print 'StartNUM ',startNum,'EndNum ',endNum
        if startNum%3==0 and startNum%5==0:
            listNumBoth.append(startNum)

        elif startNum%3==0:
            listNumThree.append(startNum)
        elif startNum%5==0:
            listNumFive.append(startNum)
        else:
            print 'number not divisible',startNum
    else:
        print 'while loop ended'

main()

3 Answers3

1

endNum is a string and startNum a number....

Your problem should be here...

try with int(endNum) to parse the input string to a number.

inigoD
  • 1,681
  • 14
  • 26
1

raw_input returns a string so you're not doing the integer comparison you think you're doing.

Convert endNum to an integer:

endNum = int(raw_input('please enter the end number'))
Josh B
  • 1,748
  • 16
  • 19
  • Thanks!!! Appreciate the input. Now that issue is resolved. Just wondering why it didn't throw error stating cannot compare string to integer. – AspiringDataAssasin Jul 04 '14 at 18:59
  • Backround reading: http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int http://stackoverflow.com/questions/2384078/why-is-0-true-in-python – Josh B Jul 06 '14 at 22:52
1

raw_input will return a string not integer. You need to convert it to integer value:

while True:
    endNum = raw_input('please enter the end number')
    try:
        endNum = int(endNum)
        break
    except ValueError:
        print "Please enter a valid number"
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164