The issue with your code is that the counter
variable inside the counter()
function is not being incremented. As a result, the while
loop will never reach the condition where counter
equals 5, leading to an infinite loop.
Here's the corrected version of your code that properly increments the counter
and avoids the infinite loop:
def counter():
counter = 0
while counter != 5:
print("counter is less than 5")
counter += 1 # This increments the counter by 1
counter()
Explanation:
- The line
counter += 1
increments the value ofcounter
by 1 in each iteration of the loop. - Once the value of
counter
reaches 5, the loop will exit and the function will end.
You can run this code, and it will print "counter is less than 5" five times before exiting the loop.