1

My code is not stopping. I'm hoping someone could explain what I'm doing wrong.

what I'm trying to do is run the program, give it a number and have it loop until that number is reached. I give the program x, x is given to counting. and it should check i to x each time.

numbers = []
x = raw_input("> ")
def counting(num):
    i = 0
    while i < num:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i
counting(x)
print "The numbers: "

for num in numbers:
    print num
Ranger Skip
  • 105
  • 8

2 Answers2

3

x = int(raw_input("> ")), you are comparing a string to an int. You can also use range:

def counting(num):
    for i in range(num):
        print "At the top i is %d" % i
        numbers.append(i)
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % (i + 1)

If you actually want to print "At the bottom i is %d" % i to print only the last i, move it outside the loop.:

def counting(num):
    for i in range(num):
        print "At the top i is {}".format(i)
        numbers.append(i)
        print "Numbers now: {}".format(numbers)
    print "At the bottom i is {}".format(i)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

In Python 2, raw_input() returns a string (like Python 3's input()). You are sending this directly to your counting function.

Also in Python 2, you can compare strings and integers and Python won't complain. This gives you unexpected results when you were trying to work with just one or the other, which is probably why Python 3 will raise an error when you compare strings and integers.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97