How to use raw_input() with while-loop

别说谁变了你拦得住时间么 提交于 2019-12-13 13:31:58

问题


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


回答1:


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



回答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 = 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


来源:https://stackoverflow.com/questions/17394495/how-to-use-raw-input-with-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!