0
votes

the following while loop keeps running continuously and I have no idea why

i=False
print(i)
while True:
    if i==False:
        i=True
        print(i)

i was expecting one print of "False" and one print of "True" but it keeps looping continuously printing the True statement into infinity even though it should break the while condition once i updates its value.

Anyone know why?

1
while True: -- True is always True - costaparas
You should be checking i -- since that's what you're changing. Based on your code, you may want while not i:. - costaparas
thanks, could you give an example of how you would code it? - beginner_python
There's no much more to add here -- you've made a typo/logical error, and its a one line fix. - costaparas
BTW PEP712 suggests the comparison if i is False rather than using ==. Though if not i would also be acceptable here. - costaparas

1 Answers

0
votes

This code of yours has an infinite loop as condition mentioned with while is always evaluated as True. That's why it keep on running for infinite time. To achieve your task i will suggest you to add a break statement after print(i) inside while loop.

i=False
print(i)
while True:
    if i==False:
        i=True
        print(i)
        break

That will solve your problem. However there is another way around to achieve you task. As you need to print True and False just one time, you can do this:

print(False)
print(True)

Hope this will solve your problem.