0

I am writing Python code counting up to the number the user provides, but I get into an infinite loop when running the code. Please note I tried commenting out lines 3 and 4 and replaced "userChoice" with a number, let's say for example 5, and it works fine.

import time

print "So what number do you want me to count up to?"
userChoice = raw_input("> ")

i = 0
numbers = []

while i < userChoice:
    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
    time.sleep(1)

print "The numbers: "

for num in numbers:
    print num
    time.sleep(1)
William Chiang
  • 85
  • 2
  • 12
  • So is there a code that I am missing? – William Chiang Nov 21 '16 at 03:44
  • What is the input that causes the error and can you provide a sample of the output when the error is occurring? – Spencer D Nov 21 '16 at 03:44
  • If I pick any number, the code will print the number +1 indefinitely – William Chiang Nov 21 '16 at 03:45
  • So what number do you want me to count up to? > 5 At the top i is 0 Numbers now: [0] At the bottom i is 1 At the top i is 1 Numbers now: [0, 1] At the bottom i is 2 At the top i is 2 Numbers now: [0, 1, 2] At the bottom i is 3 At the top i is 3 Numbers now: [0, 1, 2, 3] At the bottom i is 4 At the top i is 4 Numbers now: [0, 1, 2, 3, 4] At the bottom i is 5 At the top i is 5 Numbers now: [0, 1, 2, 3, 4, 5] At the bottom i is 6 At the top i is 6 Numbers now: [0, 1, 2, 3, 4, 5, 6] At the bottom i is 7 At the top i is 7 – William Chiang Nov 21 '16 at 03:47
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – ruohola May 04 '19 at 14:20

2 Answers2

2

raw_input returns a string, not int. You can fix the issue by converting user response to int:

userChoice = int(raw_input("> "))

In Python 2.x objects of different types are compared by the type name so that explains the original behavior since 'int' < 'string':

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

niemmi
  • 17,113
  • 7
  • 35
  • 42
1

You are comparing a number with a string in:

while i < userChoice:

The string will always be greater than the number. At least in Python 2 where these are comparable.

You need to turn userChoice into a number:

userChoice = int(raw_input("> "))
Dan D.
  • 73,243
  • 15
  • 104
  • 123