在break语句后不在while循环之外执行代码

时间:2020-08-16 19:47:16

标签: python python-3.x

我正在尝试退出无限循环,但我陷入其中。我尝试过以不同的方式使用break语句,但结果始终相同:程序退出循环后终止,并且不执行其余代码。为解决此问题,我应该更改代码中的什么?

moylist = []
import copy
while True:
    thing = input()
    if thing == '':
      break
    moylist.append(thing)
moylist.insert(-2, 'and')
moynovlist = copy.deepcopy(moylist)
moynovlist1 = moynovlist[-2:] # cutting the end
perv = str(moynovlist1)
perv1 = perv[:4] + perv[4:] #without the comma (and ...)

1 个答案:

答案 0 :(得分:1)

代码运行正常!您认为它退出整个程序而不是while循环的原因是因为您没有任何打印语句。只需在程序末尾添加const data = [ /* ...the above input data... */ ]; let result = []; let prevId = null; for (let elem of data) { let currId = elem.nestedObj.id; if (currId === prevId) { result[result.length - 1].push({...elem}); } else { result.push([{...elem}]); } prevId = currId; } ,您就会看到print(perv1)发生了变化,这意味着循环已正确退出。