只是尝试编写一个程序,将用户输入并将其添加到列表'数字'中:
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
我在这里缺少一些基本规则吗?
答案 0 :(得分:7)
raw_input
返回的字符串不是整数:
所以,
>>> 1 <= "4" <= 20
False
使用int()
:
i = int(raw_input('>> '))
如果您只从用户那里获取一条输入,则只使用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
答案 1 :(得分: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