Home > OS >  Iteration in python
Iteration in python

Time:01-03

I am not getting the expected result from this code below, as I expect a display of numbers excluding 4.

z = 0

while z < 6:
    if z == 4:
        continue
    z = z   1
    print(z)

I get numbers from 1 to 4

CodePudding user response:

I think the heart of the post has to do with what does continue do?

From tutorialspoint.com

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.

So they'd suggest something like the below instead.

z = -1

while z < 6:
    z = z   1
    if z == 4:
        continue
    print(z)

CodePudding user response:

You need to increment z first before the if condition to avoid going into an infinite loop. This will solve your problem. Just a simple edit in your code:

z = 0

while z < 6:
    z  = 1
    if z == 4:
        continue
    print(z)

CodePudding user response:

z = 0

while z < 6:
    z = z   1
    if z == 4:
       continue
    print(z)

CodePudding user response:

The problem is your condition

if z == 4:
    continue

when z is equals to 4 your loop continues without incrementing the value of z to 5 so on so forth.

Below code should get you desired output

z = 0
while z < 6:
    if z != 4:
        print(z)
    z  = 1
  • Related