我不了解如何在用户输入中使用for循环。更具体地说,我想创建一个for循环,如果满足条件,则会要求更多用户输入。
例如,我正在考虑做以下事情:
number = input("what is the value")
for number in numbers:
number = input("what is the value")
numbers = [1,2,3]
if number = numbers
print (number)
以上是一个通用代码,我的目标是获取循环的输入(值是什么)。
如果我按照上面显示的方式进行,问题会在开头重复两次。
如果我删除第1行,我的变量是未定义的。如果我稍后删除第3行,那么依赖于数字变量的代码将被取消定义。
有人能告诉我一个更好的方法来解决这个问题吗?
答案 0 :(得分:0)
您可以使用while
循环
while True:
num = raw_input("what is the value ")
num = int(num)
number = [1,2,3]
if num in number:
pass
else:
break
正如你所说num
中存在number
然后循环将运行,否则它将退出
答案 1 :(得分:0)
尝试这个运行5次的简单for循环并询问用户的输入。如果她输入的数字与循环变量匹配,则打印成功消息。快乐编程:)
for i in range(5): #Runs this loop 5 times
number = input("what is the value ? :")
if number == i:
print "You are correct"
else:
print "The correct answer is ", i
日志:
what is the value ? :1
The correct answer is 0
what is the value ? :1
You are correct
what is the value ? :2
You are correct
what is the value ? :1
The correct answer is 3
what is the value ? :1
The correct answer is 4
更新:如果你非常喜欢动物
animals = ['cat', 'dog', 'macaw', 'dove']
for ani in animals:
animal = raw_input("what is the value ? :")
if animal == ani:
print "You are correct"
else:
print "The correct answer is ", ani
日志:
what is the value ? :dog
The correct answer is cat
what is the value ? :cat
The correct answer is dog
what is the value ? :macaw
You are correct
what is the value ? :test
The correct answer is dove