(there used to be python code here)
EDIT: My apologies, didn't realize this was homework. I reeeally need to check tags before answering. Here's an explanation of what needs to happen.
Obviously you know that you're trying to output consecutive numbers from 1 to 50, so you'll need a counter. You've figured out that it'll require a range()
call, but it needs to be from 1 to 51, not from 2 to 50.
The reason the range()
call needs to be from 1 to 51 is this: it will start the variable i
at 1
, then check to see if it has reached its goal (51
) before looping. If the goal is reached (meaning if i == 51
) it will quit the loop without executing the loop's code. So rather than go from 1 to 50, you go from 1 to 51 so that we don't skip the 50th iteration.
Next, you're going to want to have the numbers appear on-screen. But using python's print
command prints each number on a new line! That's obviously not what you want. So you're going to have to create a buffer string to append each number to until you're ready to print the line. You can call it 'output' or whatever.
Personally, I like to clear the buffer BEFORE the for
loop just to be sure no residual memory traces find their way into the output. Call me paranoid. So I write output = ""
on a line before the loop.
Now you've got a buffer string, all you need to do is follow a logical flow:
- Add
i
to the buffer output
.
- If
i
is a multiple of 5, print the buffer output
and reset it back to an empty string. (We do this so that we can start the buffer for the next line.)
- If
i
is NOT a multiple of 5, add a comma to the output
buffer, so that the next number added will be after the comma.
- Continue our loop.
These steps should be pretty simple to figure out. Step 2 you've already seen before... To check if a number is a multiple of another number, simply use %
. If A % B == 0
then A is a multiple of B.
This should be a pretty straightforward explanation for how to solve this problem. Hope it helps.
And sorry for ruining your learning experience by posting the answer! Now you'll understand why the answer works.