0

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?

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

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.