1
a = raw_input ("enter a number")
i = 0
numbers = []

while i < a:
    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

print "The numbers: "

for num in numbers:
    print num   

so I'm following lpthw and was just messing with the code, why is it when I use raw_input and enter a number like 6 this loop turns into a infinite loop? shouldn't i = i + 1 be there to stop this from happening?

inkplay_
  • 197
  • 1
  • 13
  • 6
    Because an integer is always less than a string in Python 2. – Ashwini Chaudhary Feb 02 '14 at 19:15
  • I was wrong about this being the answer, but you *are* mixing tabs and spaces. This is **bad**. I don't know why it runs; maybe this is only a problem in your copy/paste to SO, but be sure you're using only spaces. – mhlester Feb 02 '14 at 19:19
  • fix indents btw... like that the code will just not even compile. – Loïc Faure-Lacroix Feb 02 '14 at 19:19
  • 2
    Is `i = i + 1` inside the while loop? Please fix your indentation. And it's better to write it as `i += 1`. –  Feb 02 '14 at 19:43

4 Answers4

9

In Python 2.7, raw_input returns a str(string). So when you compare i < a, you are comparing an integer with a string and it will always return True.

To fix this, cast your input to an integer:

a = int(raw_input(...))

Note: As @AshwiniChaudhary commented, comparing (with <, <=, > or >=) an integer with a string in Python 3.x will raise an Exception:

TypeError: unorderable types: int() <operator> str()
Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

raw_input return a string. Your variable a is a string and strings are greater than ints in python.
You need to convert a to an int:

a = int(raw_input("enter a number"))
Ishaan
  • 886
  • 6
  • 12
1

If you use raw_input, then a will be a string. You need an int, for the i < a comparision to work as expected. Use input instead of raw_input.

For future reference, input was removed in Python 3 and raw_input renamed to input, so you will need int(input (...)) in Py3.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
1

You are doing two things that can lead to the infinite loop.

  1. The tabs and spaces are mixed up, python cares about indentation, so make sure that i = i + 1 is aligned with numbers.append(i)

  2. The actual reason why it is keeping on going is that when python collects raw_input, it transforms it into a string, not an integer, so the comparison does not work as you'd expect. Change to this and it will work as expected:

a = int(raw_input ("enter a number"))

migueldavid
  • 319
  • 1
  • 3
  • 11