Home > Enterprise >  Why it doesn't escape while loop although condition changes to False?
Why it doesn't escape while loop although condition changes to False?

Time:08-15

condition = True
while condition:
  break
  print("Hello world!")

This one won't print "Hello world!" But,

condition = True
while condition:
  condition = False
  print("Hello World!")

This one will print "Hello wolrd!"

Why is it print "Hello wolrd!" although condition changed to False before print?

CodePudding user response:

The comment section has explained pretty much everything in a concise manner. The loop won't check the condition once it is entered.

I think the code you are looking for is:

condition = True
while condition:
  condition = False
  if condition: print("Hello World!")

CodePudding user response:

Because this is not how loops work. Loop check condition only at start before execution of statements inside of it. As you can see it prints "Hello World!" only once because at start condition was True but at the end of the loop condition was False

CodePudding user response:

Let us go through your code. In code snippet one, condition is set True. The loop checks for condition, it's true. However, on the next step you have a break statement. This causes the loop to cease. Thus, it does not print "Hello World!"

In code snippet 2, condition is set True. Again, the loop checks for condition and finds it to be true. Then, on the next line condition is set False. We are still inside the loop and haven't terminated it. Now, it prints "Hello World!". On the next iteration of the loop, condition is False, and the loop terminates.

Hope this helps.

CodePudding user response:

In the first case after brake statement the other statements will not be executed inside while scope. In the second statement firstly, while loop executed and condition changed to False but there is not brake statement. So, print statement executed. After that while will not be executed because condition is False.

  • Related