0

I'm working on a practice problem that says, "Use a "while" loop to print out every fifth number counting from 1 to 1000."

I can't seem to make it work.

This is what I've tried so far (as well as several small tweaks of this).

num = 1

while num in range(1, 1001):
    if num % 5 == 0:
        num += 1
print(num)

Thank you!

2
  • 1
    print range(1, 1001, 5) ? Commented Mar 27, 2019 at 14:38
  • @khachik use a "while" loop Commented Mar 27, 2019 at 14:42

3 Answers 3

4

You're close. You want to print out every time the condition matches, but increment regardless of the condition.

num = 1

while num in range(1, 1001):
    if num % 5 == 0:
        print(num)  # print must be inside the condition
    num += 1  # the increase must be done on every iteration
Sign up to request clarification or add additional context in comments.

6 Comments

you don't need to instatiate num at the begining. You can remove that line.
That's it! Thank you for your help!
@narm: yes you have, this is not a for loop.
Yeah, it doesn't work if I remove the first line. It works exactly the way you wrote it @Toby
@Toby yeah i messed up, but the use of that instantiation with range() just seems strange.
|
3

I would say Python style would be more like:

print(list(range(0, 1001, 5)[1:]))

Got you, yes then for while loop it looks like:

num = 1
while num < 1001:
    if not num % 5:
        print(num)
    num += 1

1 Comment

That is better, but the exercise was to use a while loop 😊
1
for num in range(1, 1001):
    if num % 5 == 0:
        print(num)

You were pretty close, this should work.

@Wolf comment is also very helpful for you and relevant!

5 Comments

You need to use a "while" loop
I can do it with a for loop :) Thank you! I can't figure out how to do it with a while loop.
Alright, I was just working on the solution with a while-loop. :) You are welcome!
I'm sorry, what I mean is that the for loop you wrote was helpful, but I need to know how to do it while a while loop :)
Look up the recent answers. They provide the solution. :)

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.