inkplay_
inkplay_

Reputation: 307

Why is this a infinite loop

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?

Upvotes: 1

Views: 159

Answers (4)

migueldavid
migueldavid

Reputation: 339

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"))

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

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()

Upvotes: 9

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

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.

Upvotes: 1

Ishaan
Ishaan

Reputation: 886

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"))

Upvotes: 1

Related Questions