I want to print odd numbers within a range using Python with the code below, but I don't understand what is wrong with it and it only prints 1 and stops.
a=1
while a<11:
if a%2==0:
continue
print(a)
a+=1
I want to print odd numbers within a range using Python with the code below, but I don't understand what is wrong with it and it only prints 1 and stops.
a=1
while a<11:
if a%2==0:
continue
print(a)
a+=1
The problem is that you don't increment a when it's not odd in the if clause.
a=1
while a<11:
if a%2==0:
a+=1
continue
print(a)
a+=1
You must increment a also when it's even, else it will be stuck in an infinite loop at a=2.
A better variation would be to avoid continue and do as follows:
a=1
while a<11:
if a%2!=0:
print(a)
a+=1
continue is not needed, saying using continue is a bad practice is not true at all. There is nothing wrong with using continue.x = 1
while x < 15:
if x % 2 != 0:
print(x)
x = x + 1
This is how you do it. Main issue with your code is that continue skips everything, including the increment. Meaning your code causes an infinite loop. Continue skips all other lines in that iteration of a loop and goes to a new one, meaning a never increments meaning a is always less than 11.