How to use raw_input() with while-loop

Amon picture Amon · Jun 30, 2013 · Viewed 10.9k times · Source

Just trying to write a program that will take the users input and add it to the list 'numbers':

print "Going to test my knowledge here"
print "Enter a number between 1 and 20:"

i = raw_input('>> ')
numbers = []

while 1 <= i <= 20 :
    print "Ok adding %d to numbers set: " % i 
    numbers.append(i)

    print "Okay the numbers set is now: " , numbers

However when I execute the program it only runs to raw_input()

Going to test my knowledge here
Enter a number between 1 and 20:
>>> 4

Is there some fundamental rule I'm missing here??

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Jun 30, 2013

raw_input returns a string not an integer:

So,

>>> 1 <= "4" <= 20
False

Use int():

i = int(raw_input('>> '))

Use just if, if you're only taking a single input from user:

if 1 <= i <= 20 :
    print "Ok adding %d to numbers set: " % i 
    numbers.append(i)

    print "Okay the numbers set is now: " , numbers

Use while for multiple inputs:

i = int(raw_input('>> '))
numbers = []

while 1 <= i <= 20 :
    print "Ok adding %d to numbers set: " % i 
    numbers.append(i)
    i = int(raw_input('>> '))                   #asks for input again
print "Okay the numbers set is now: " , numbers