a = 10
counter = 0
condition = (counter<3)
while condition:
a= a +1
print (a)
counter = counter + 1
4 Answers
Because condition
is calculated once and never is updated. So, condition
is always True
even though counter
is updated.
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
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
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
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:
, orwhile condition: condition = (counter < 3)
. In other words,condition = (counter < 3)
evaluates toTrue
, and is equal to writingcondition = True
.