honor_roadman
honor_roadman

Reputation: 11

I got different results for a while loop and for loop in python (check the codes)

FOR THE FIRST CODE:

num = 1

while num<=100:
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")
    num+=1

OUTPUT: 1 2

FOR THE SECOND CODE:

for num in range(1, 101):
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")

OUTPUT:

1 2 4 7 8 11 13 14 16 17 19 22 23 26 28 29 31 32 34 37 38 41 43 44 46 47 49 52 53 
56 58 59 61 62 64 67 68 71 73 74 76 77 79 82 83 86 88 89 91 92 94 97 98

Upvotes: 0

Views: 236

Answers (5)

Anupam Chaplot
Anupam Chaplot

Reputation: 1316

Use below logic

        num = 1

        while num <= 100:
            if num % 3 == 0 or num % 5 == 0:
                num += 1
                continue
            print(num, end=" ")
            num += 1

Upvotes: 0

Batata
Batata

Reputation: 96

It's an infinite loop. Your program never terminates after it reaches num == 3. It goes to the if statement and the continue takes it back to the while check.

Upvotes: 0

zkldi
zkldi

Reputation: 94

Your code does not call increment 1 in the while loop inside the if statement, it never gets past 3.

Upvotes: 0

Zaraki Kenpachi
Zaraki Kenpachi

Reputation: 5730

You need to add incrementation before you continue

num = 1
while num<=100:
    if num%3==0 or num%5==0:
        num += 1
        continue
    print (num)
    num+=1

Upvotes: 1

Mert K&#246;kl&#252;
Mert K&#246;kl&#252;

Reputation: 2231

You need to edit your while code in order to achieve same result. In your while loop if num%3 == 0 or num%==5, then the program not executing num += 1, so your program doesn't increment 1. You need to change like this:

num=0
while num <= 100:
    num+=1
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")

Upvotes: 1

Related Questions