循环不会中断
我正在创建一种数据库,使用从用户读取的列表。当用户输入finish
时,我希望 while 循环停止。但是,由于某种原因,我需要输入两次 finish
才能打破循环。
另外,返回后列表为空。
def readNames():
nameList = []
count = 0
while count != -1: #infinite loop
addList = raw_input("Please enter a name: ")
if addList == 'finish':
return nameList
break
nameList.append(addList)
print nameList
我正在调用它并检查它是否适用
readNames()
print readNames()
此外,这是输出
Please enter a name: Dave
['Dave']
Please enter a name: Gavin
['Dave', 'Gavin']
Please enter a name: Paul
['Dave', 'Gavin', 'Paul']
Please enter a name: Test1
['Dave', 'Gavin', 'Paul', 'Test1']
Please enter a name: finish
Please enter a name: finish
[]
>>>
I'm creating a sort of database, using a list that is read in from the user. When the user enters finish
I want the while loop to stop. However, for some reason I need to enter finish
TWICE for it to break the loop.
Also, the list is empty after being returned.
def readNames():
nameList = []
count = 0
while count != -1: #infinite loop
addList = raw_input("Please enter a name: ")
if addList == 'finish':
return nameList
break
nameList.append(addList)
print nameList
I'm invoking it and checking if it worked with
readNames()
print readNames()
Also, here is the output
Please enter a name: Dave
['Dave']
Please enter a name: Gavin
['Dave', 'Gavin']
Please enter a name: Paul
['Dave', 'Gavin', 'Paul']
Please enter a name: Test1
['Dave', 'Gavin', 'Paul', 'Test1']
Please enter a name: finish
Please enter a name: finish
[]
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您这样做时,
您将运行该函数两次。在第二次运行时,您只需输入“完成”,这就是您的列表仍为空的原因。
你想做的是这样的:
When you do
you run the function twice. On the 2nd run you just enter "finish" and thats why your list remains empty.
What you want to do is this:
我认为您的调用代码意外地调用了 readnames() 两次。
I think your calling code is accidentally invoking
readnames()
twice.啊,在您发布代码后,我可以看到问题:
您调用
readNames
,按计划从 stdin 读取这些名称,正确返回
读取的名称,然后丢弃结果,因为您没有将其分配给任何内容 (names = readNames()
)。然后,您再次调用readNames
,您会发现它似乎没有退出循环(它确实退出了,但您告诉它再次循环)。再次输入finish
,第二次调用readNames
结束,没有输入任何名称(nameList
是一个局部变量,因此在函数执行结束),所以你返回[]
。要解决此问题,(1) 温习一般编程知识;) 和 (2) 执行类似
names = readNames()
; 的操作;打印姓名
。Ah, after you posted your code, I can see the issue:
You call
readNames
, read those names from stdin as planned, properlyreturn
the read names and then throw the result away because you don't assign it to anything (names = readNames()
). Then you callreadNames
again, and it appears to you as if it didn't exit the loop (it did, but you told it to loop again). You typefinish
again, and the second invocation ofreadNames
ends without any names entered (nameList
is a local variable, so it is lost after the function execution ends), so you get back[]
.To fix this, (1) brush up your general programming knowledge ;) and (2) do something like
names = readNames()
;print names
.不能替换
为吗
?
詹姆斯
Could you not replace
With
?
James