Skip to content Skip to sidebar Skip to footer

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

Solution 1:

raw_input returns a string not an integer:

So,

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

Use int():

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

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

if1 <= 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 = []

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

Solution 2:

To add to Ashwini's answer, you will find that raw_input will only run once. If you want to keep prompting the user, put the raw_input inside the while loop:

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

numbers = []
i = 1while1 <= i <= 20 :
    i = int(raw_input('>> '))
    print"Ok adding %d to numbers set: " % i 
    numbers.append(i)

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

Post a Comment for "How To Use Raw_input() With While-loop"