Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use raw_input() with while-loop

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??

like image 510
Amon Avatar asked Jan 13 '23 00:01

Amon


1 Answers

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
like image 142
Ashwini Chaudhary Avatar answered Jan 25 '23 19:01

Ashwini Chaudhary