如何在 while 循环中使用 raw_input() [英] How to use raw_input() with while-loop
本文介绍了如何在 while 循环中使用 raw_input()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只是想写一个程序来接收用户输入并将其添加到列表数字"中:
print "Going to test my Knowledge here"打印输入一个 1 到 20 之间的数字:"i = raw_input('>>')数字 = []而 1 <= i <= 20 :打印好的,将 %d 添加到数字集:" % inumbers.append(i)打印好的,现在设置的数字是:",数字
但是当我执行程序时它只运行到 raw_input()
在这里测试我的知识输入 1 到 20 之间的数字:>>>4
我在这里遗漏了一些基本规则吗??
解决方案
raw_input
返回字符串而不是整数:
所以,
<预><代码>>>>1 <= "4" <= 20错误的使用int()
:
i = int(raw_input('>> '))
仅使用 if
,如果您只从用户那里获取一个输入:
如果 1 <= i <= 20 :打印好的,将 %d 添加到数字集:" % inumbers.append(i)打印好的,现在设置的数字是:",数字
将 while
用于多个输入:
i = int(raw_input('>> '))数字 = []而 1 <= i <= 20 :打印好的,将 %d 添加到数字集:" % inumbers.append(i)i = int(raw_input('>> ')) #再次请求输入打印好的,现在设置的数字是:",数字
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??
解决方案
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
这篇关于如何在 while 循环中使用 raw_input()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文