
Title:
Print Numbers Solution  Intro to Computer Science

Description:

Here's one way to define "print_numbers":

so we're going to make a procedure using "def".

It takes 1 input.

We'll use the name "n" for our input.

That's the number that we go up to.

Now, to do the loop, we need to have a new variable

that keeps track of the loop iterations.

We'll use "i" for that, and we start with 1that's the first number to print out.

We need the loop now, so we have the "while"

and the test that we want is we want to keep going,

up to and including the number, "n".

So we want to print the numbers, all the way from 1 up to and including "n".

So our test will now be a less than or equal to test.

We want to keep going as long as "i" is less than or equal to "n".

Once "i" gets bigger than "n", that's when we should stop.

What we do in the loop body is print the value of "i"

and add 1 to "i".

We don't need to return anything; the only point of the procedure,

as we were asked to write it, was to print out the numbers.

So now let's do a test: we'll print the numbers up to 3,

and there we get the output, printing the numbers 1, 2, 3.

There are lots of other ways we could have written this.

Another approach would be to start with "i" equals zero,

make the test condition "i" is less than "n".

So now we're stopping as soon as "i" is equal to "n".

For this to print out the correct numbers, though, now we need to move the print.

We want the print to be after we added 1 to "i",

so the first number we print is supposed to be a 1, which will be the case here.

And the final number we print should be "n", which is the case here.

Once the value of "i" is "n", this test will be False

and we don't go through the loop anymoreso

when we run this, we get the same result, printing 1, 2, 3.

So as another test, let's see what happens when we pass in zero.

And when we run this, it doesn't print anything.

That's because when "i" is zero, "i" less than "n" evaluates to False.

Zero is not less than zero, so we don't go through the loop at all

and don't print anythingwhich seems like a pretty sensible thing.

Since we said print the numbers between 1 and the target number,

if the target number is zero, not printing anything sort of makes sense.