1
a = 10
counter = 0
condition = (counter<3)
while condition:
    a= a +1
    print (a)
    counter = counter + 1

imagedescription

2
  • 3
    Because condition is only evaluated once. If you want to run it every time you have to put it inside the while loop (while counter < 3:, or while condition: condition = (counter < 3). In other words, condition = (counter < 3) evaluates to True, and is equal to writing condition = True.
    – Thymen
    Commented Apr 26, 2021 at 19:05
  • 1
    @Thymen Please don't put answers in the comments; post an answer instead please
    – wjandrea
    Commented Apr 26, 2021 at 19:21

4 Answers 4

7

Because condition is calculated once and never is updated. So, condition is always True even though counter is updated.

6

In the line

condition = (counter<3)

Python executes the comparison on the right and assigns it to "condition" on the left. This happens once before the loop and condition is always True. You seem to be under the impression that condition is a function, but it's not. Its right hand side is only run once, before the loop begins.

The easy fix is to do the operation in the loop condition so that it is re-executed every time.

a = 10
counter = 0
while counter < 3:
    a= a +1
    print (a)
    counter = counter + 1
2

Your condition never changes inside the loop. You must update your condition inside of the loop looking like this:

a = 10
counter = 0
condition = counter < 3
while condition:
    a= a +1
    print (a)
    counter = counter + 1
    condition = counter < 3

But this violates the DRY (don't repeat yourself) principle. I would completely remove your condition variable and implement your condition with your logic like so:

a = 10
counter = 0
while counter < 3:
    a= a +1
    print (a)
    counter = counter + 1
1

When you initially assigned condition it was given the value 'True'. Its value doesn't change when you increase counter. A better method would be:

a = 10
counter = 0
while counter < 3:
    a = a + 1
    print(a)
    counter = counter + 1

Not the answer you're looking for? Browse other questions tagged or ask your own question.