While Loop- Continue Statement printing duplicate values

Viewed 40

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
2 Answers

Correct code to do the required operation is mentioned below, please see if this solves your purpose.

for i in range(10): 
    if i % 3 == 0: 
        continue
    print(I)

Hi @Tech_Nut Welcome to Stackoverflow 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.

Related