简体   繁体   English

而与raw_input创建无限循环

[英]while with raw_input creating an infinite loop

In these lines: 在这些行中:

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

How to do the loop break? 循环中断怎么办? Thanks! 谢谢!

list.append returns None. 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)

This is the way to do it 这是做到这一点的方法

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

Just check for the last element added to 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

You are assigning b to the result of a list append which is None. 您正在将b分配给列表附加的结果,即None。 Even if you were lookking at foo, you would be looking at the list created by the foo.append and then comparing it to the charcter 'N'. 即使您正在查找foo,也要查看foo.append创建的列表,然后将其与字符“ N”进行比较。 Even if you only type N at the input, the value of foo would at least look like ['N']. 即使仅在输入中键入N,foo的值也至少看起来像['N']。 You could eliminate b altogether with: 您可以将b完全消除:

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

Though this would leave the 'N' character in your list. 尽管这会将'N'字符保留在您的列表中。 Not sure if that is intended or not. 不知道这是否是故意的。

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

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