How to use raw_input () with while-loop

Just try writing a program that will introduce users and add them to the list of "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 run the program, it only works with raw_input ()

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

Is there any fundamental rule that I'm missing here?

+4
source share
2 answers

raw_input returns a non-integer string:

So,

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

Use int() :

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

Use only if if you accept only one input from the 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 
+7
source

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

 print "Going to test my knowledge here" print "Enter a number between 1 and 20:" numbers = [] i = 1 while 1 <= 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 
+2
source

Source: https://habr.com/ru/post/1488992/


All Articles