繁体   English   中英

而与raw_input创建无限循环

[英]while with raw_input creating an infinite loop

在这些行中:

foo = []

a = foo.append(raw_input('Type anything.\n'))
b = raw_input('Another questions? Y/N\n')

while b != 'N':
    b = foo.append(raw_input('Type and to continue, N for stop\n'))
    if b == 'N': break

print foo

循环中断怎么办? 谢谢!

list.append返回None。

a = raw_input('Type anything.\n')
foo = [a]
b = raw_input('Another questions? Y/N\n')

while b != 'N':
    b = raw_input('Type and to continue, N for stop\n')
    if b == 'N': break
    foo.append(b)

这是做到这一点的方法

foo = []

a = raw_input('Type anything.\n')
foo.append(a)
b = raw_input('Another questions? Y/N\n')

while b != 'N':
    b = raw_input('Type and to continue, N for stop\n')
    if b == 'N': break
    foo.append(raw_input)

print foo

只需检查添加到foo的最后一个元素:

while b != 'N':
    foo.append(raw_input('Type and to continue, N for stop\n'))
    if foo[-1] == 'N': break   # <---- Note foo[-1] here

您正在将b分配给列表附加的结果,即None。 即使您正在查找foo,也要查看foo.append创建的列表,然后将其与字符“ N”进行比较。 即使仅在输入中键入N,foo的值也至少看起来像['N']。 您可以将b完全消除:

while True:
    foo.append(raw_input('Type and to continue, N for stop\n'))
    if 'N' in foo: break

尽管这会将'N'字符保留在您的列表中。 不知道这是否是故意的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM