Ad

While Loop Over Numbers Doesn't Seem To Be Working

- 1 answer

I am new to python and I am trying run this piece of code, however, the while loop doesn't seem to be working. Any ideas?

def whilelooper(loop):
    i = 0
    numbers = []


    while i < loop:
        print "At the top i 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


print "Enter a number for loop"
b = raw_input(">")

whilelooper(b)
Ad

Answer

Your input is inputted as a string type, but the comparator

while i < loop: 

is expecting both i and loop to be of type int (for integer), in order to be able to compare them.

You can fix this by casting loop to an int:

def whilelooper(loop):
    i = 0
    numbers = []
    loop = int(loop)
    ...
Ad
source: stackoverflow.com
Ad