1

This is part of a tutorial. My goal was to take an input from user and then increment it while a condition is true.

inputNum = raw_input("What is max number?")

def incrementF(greatest):
    i = 0
    numbers = []

    while i < greatest:
        print "At the top of the list numbers is %d" % i
        numbers.append(i)

        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

    print "The numbers:"

    for num in numbers:
        print num

incrementF(inputNum)

When I run the script and type anything in for inputNum, rather than a few lines of output, I appear to run into an infinite loop.

For example, is the raw input prompt gave 10, I'd have expected to see something like:

At the top of the list numbers is 0,
Numbers now: 0,
0
At the top of the list numbers is 1,
Numbers now: 1,
1

I've read over my script several times and cannot see. I suspect it could have something to do with indenting? But I'm not sure.

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

1 Answers1

10

As quoted in the docs for raw_input:

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

So, greatest will be a string because you used raw_input to get it.

Furthermore, in Python 2.x, strings are always evaluated as being greater than integers*:

>>> 1 < 'a'
True
>>> 100000000000 < 'a'
True
>>>

This means that the condition of your while-loop will always evaluate to True because greatest will always be evaluated as being greater than i. Thus, you get an infinite loop.

You can fix this problem simply by making greatest an integer like i:

inputNum = int(raw_input("What is max number?"))

*Note: If you would like some more information on this, see How does Python compare string and int?

Community
  • 1
  • 1