Home > Blockchain >  Why Continue in While loop is not working in Python?
Why Continue in While loop is not working in Python?

Time:01-07

Hello while I was practicing while loop in Python my code was not giving any outputs whatsoever. I am learning python from books only, so it may sound basic: but where is the problem in this code? I was trying to print integers less than 100 which are not divisible by 5.

x=0
while (x<101):
    if (x%5==0):
        continue
    
    print (x, end=" ")
    x=x 1

I was trying to print integers less than 100 which are not divisible by 5

CodePudding user response:

continue goes back to the beginning of the loop, skipping over the rest of the body. This means it skips over x = x 1. So you keep testing the same value of x.

Instead of a while loop, use a for loop, so the increment isn't in the body that you skip over.

for x in range(100):
    if x % 5 == 0:
        continue

    print(x, end=" ")

If you really want to use while and continue, you can duplicate the code that increments x.

while x < 101:
    if x % 5 == 0:
        x  = 1
        continue

    print(x, end=" ")
    x  = 1

Or you could move the increment before the test

while x < 101:
    x  = 1
    if x % 5 == 1:
        continue

    print(x-1, end=" ")

But notice that this makes it more complicated because you have to subtract 1 when printing to get the value from before the increment.

CodePudding user response:

You should try stepping through your code with a debugger before posting a question here. If you had done this you would have found the problem right away.

Your code gets stuck in an infinite loop. Try this:

x=0
while (x<101):
    if (x%5 != 0):
        print (x, end=" ")
    x=x 1

CodePudding user response:

You got an infinite loop on execution...

when x is 0, it's true, the loop continue on next execution but x is not incremented. So on the next loop execution, the same result: 0 % 5 == 0 returns true

Solution: increment x before the continue;

so you'll have:

x=0
while (x<101):
if (x%5==0):
    x=x 1
    continue

print (x, end=" ")
x=x 1

This should be fine !

  • Related