为什么这段代码会进入无限循环?

Why does this code go into infinite while loop?

下面的代码进入无限循环,实际上如果我一步一步做,它应该在 i 的值变为 0 时终止,此时 while 条件变为 False.因此,while 循环应该终止。根据我的理解,输出应该是 -5 -4 -3 -2 -1 0 因为 0False 这使得 while True 条件 False。有人可以解释为什么代码没有终止并进入无限循环吗?

i = -5        # initialization
while True:   # condition
    print(i)  # statement
    i += 1

print("exit")

i的值是多少并不重要;您的循环仅考虑 True 的值,这是一个永远不会变为假的常数。

i = -5
while i != 0:  # i alone works, but this is clearer
  print(i)
  i += 1