Cha*_*ith 4 python raw-input while-loop
只是尝试编写一个程序,将用户输入并将其添加到列表'数字':
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
Run Code Online (Sandbox Code Playgroud)
但是,当我执行程序时,它只运行到raw_input()
Going to test my knowledge here
Enter a number between 1 and 20:
>>> 4
Run Code Online (Sandbox Code Playgroud)
我在这里缺少一些基本规则吗?
raw_input 返回一个字符串而不是整数:
所以,
>>> 1 <= "4" <= 20
False
Run Code Online (Sandbox Code Playgroud)
用途int():
i = int(raw_input('>> '))
Run Code Online (Sandbox Code Playgroud)
if如果您只是从用户那里获取一个输入,请使用just :
if 1 <= i <= 20 :
print "Ok adding %d to numbers set: " % i
numbers.append(i)
print "Okay the numbers set is now: " , numbers
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)