-3

A study drill at the end of the chapter asks me to make a function that calls a while loop that will count in an interval decided by the user, but I keep getting an endless loop. If I replace the x with a number, it will end, but if I leave it as x, as far as I can tell, it doesn't register the raw_input() from the user.

def counting_up():
    i = 0
    numbers = []
    print "Where do you want to end?"
    x = raw_input(">")

    print "How much would you like to increment by?"
    a = raw_input(">")

    while i < x:
        print "At the top, i is %d." % i
        numbers.append(i)

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

        print "Your numbers: ", numbers
        for num in numbers:
            print num
counting_up()
vaultah
  • 44,105
  • 12
  • 114
  • 143
Harvey M
  • 51
  • 1
  • 7

1 Answers1

0

When you get x from the raw_input() function, it stores it as a string. Then when you try to compare the number i to the string x, it's not going to behave in the way it would if the 2 were numbers.

Try converting the variables to integers so that you can compare them as numbers.

while i < int(x):
    #code

However, because you're now converting the input to an integer, your program will throw an error if the user's input isn't in the form of a number. You can either just assume they will give you the correct input, or do some error-checking like so:

x = raw_input(">")
try:
    x = int(x)
except Exception as e:
    print "You have to input a number!"
    exit()
xgord
  • 4,606
  • 6
  • 30
  • 51