beginner_python
beginner_python

Reputation: 35

Basic While loop problem when changing variable value - python

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?

Upvotes: 0

Views: 464

Answers (1)

Lokesh Raj
Lokesh Raj

Reputation: 11

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.

Upvotes: 0

Related Questions