Python 奇怪的while循环导致无限循环

Python 奇怪的while循环导致无限循环,python,while-loop,Python,While Loop,这是一个小代码片段,它导致我的程序由于无限循环而崩溃 while not stack.is_empty(): if operators[stack.peek()] >= operators[character]: result += stack.pop() while not stack.is_empty() and operators[stack.peek()] >= operators[character]: result += stack.po

这是一个小代码片段,它导致我的程序由于无限循环而崩溃

while not stack.is_empty():
    if operators[stack.peek()] >= operators[character]:
        result += stack.pop()
while not stack.is_empty() and operators[stack.peek()] >= operators[character]:
    result += stack.pop()
其中,stack是stack对象,操作符是dictionary。 但是,下面的代码不会导致无限循环

while not stack.is_empty():
    if operators[stack.peek()] >= operators[character]:
        result += stack.pop()
while not stack.is_empty() and operators[stack.peek()] >= operators[character]:
    result += stack.pop()
我的问题是:这些代码片段基本上不是一样的吗?为什么一个导致无限循环而另一个没有


谢谢,第一个继续循环并查看堆栈,检查条件是否为真,但仍在继续。在第二种情况下,当条件为false时,它将被切断

while not stack.is_empty():
    if operators[stack.peek()] >= operators[character]:
        result += stack.pop()
在这里,while循环一直运行到堆栈为空,并且您只为
=
弹出,它在堆栈中为
=运算符[character]
的次数为
true



在这里,您限制while循环,只允许它在堆栈不为空的情况下继续运行。

…这意味着您可以通过在第一个循环中添加一个
else:break
,使它们相等。