4

只是想写一个程序来接受用户输入并将其添加到列表“数字”中:

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

但是,当我执行程序时,它只运行到 raw_input()

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

我在这里缺少一些基本规则吗?

4

2 回答 2

7

raw_input返回一个字符串而不是整数:

所以,

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

使用int()

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

使用 just if,如果您只从用户那里获取一个输入:

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

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

用于while多个输入:

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
于 2013-06-30T20:23:17.450 回答
2

要添加到 Ashwini 的答案,您会发现 raw_input 只会运行一次。如果您想继续提示用户,请将 raw_input 放在 while 循环中:

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
于 2013-06-30T20:26:36.760 回答