简体   繁体   中英

Why does this code go into infinite while loop?

The following code goes into infinite loop when in fact if I do step by step, it should terminate when the value of i becomes 0 at which point while condition becomes False . Thereby, the while loop should terminate. Based on my understanding, the output should have been -5 -4 -3 -2 -1 0 since 0 is False which makes while True condition False . Can somebody please explain why the code does not terminate and goes into infinite loop?

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

print("exit")

It doesn't matter what the value of i is; your loop only considers the value of True , which is a constant that never becomes false.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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