pythonwhile-loopcontinue

While Loop- Continue Statement printing duplicate values


I am writing the following code in Python to execute a program that 'skips' out numbers in a range of 1-10 which are divisible by 3:

for i in range(10):
    while i % 3 == 0 :
        i = i + 1
        continue
    print(i)

BUT,

the output is printing out duplicate values:

1
1
2
4
4
5
7
7
8
10

Can someone please explain the error in the code? Thanks.

A program that 'skips' out numbers in a range of 1-10 which are divisible by 3:

for i in range(10):
    while i % 3 == 0 :
        i = i + 1
        continue
    print(i)

OUTPUT:

0
1
2
4
5
7
8

Solution

  • Since your question states numbers from range 1 to 10 then it rules out 0 as a response in answer also the answer by @Piyush is correct but you should look more into loops and check how they work as for and while can be used together but in different scenarios and not like the range of numbers asked by you.