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
1
  • 5
    Follow what your code does step by step: pythontutor.com Commented Mar 8, 2022 at 12:56

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Using continue as a whole is a bad practice IMO and should be avoided, which here it can be easily avoided.
Agreed. I was explaining to them the problem in their code. But I have taken your suggestion to improve my answer.
Providing both options is 100% best here. Good answer.
While in this case continue is not needed, saying using continue is a bad practice is not true at all. There is nothing wrong with using continue.
@leoOrion Agree to disagree.
2
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.

Comments

1

Her you go mate:

a=1
while a<11:
    if a%2!=0:
        print(a)
    a+=1

Comments

1

you need to add a+=1 before you continue, just know that you can write something more simple then that, and more pretty ;)

a=1
while a<11:
    if a%2==0:
        a+=1   ///add this
        continue
    print(a)
    a+=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.