English subtitles

← Print Numbers Solution - Intro to Computer Science

Get Embed Code
8 Languages

Showing Revision 6 created 05/25/2016 by Udacity Robot.

  1. Here's one way to define "print_numbers":
  2. so we're going to make a procedure using "def".
  3. It takes 1 input.
  4. We'll use the name "n" for our input.
  5. That's the number that we go up to.
  6. Now, to do the loop, we need to have a new variable
  7. that keeps track of the loop iterations.
  8. We'll use "i" for that, and we start with 1--that's the first number to print out.
  9. We need the loop now, so we have the "while"
  10. and the test that we want is we want to keep going,
  11. up to and including the number, "n".
  12. So we want to print the numbers, all the way from 1 up to and including "n".
  13. So our test will now be a less than or equal to test.
  14. We want to keep going as long as "i" is less than or equal to "n".
  15. Once "i" gets bigger than "n", that's when we should stop.
  16. What we do in the loop body is print the value of "i"
  17. and add 1 to "i".
  18. We don't need to return anything; the only point of the procedure,
  19. as we were asked to write it, was to print out the numbers.
  20. So now let's do a test: we'll print the numbers up to 3,
  21. and there we get the output, printing the numbers 1, 2, 3.
  22. There are lots of other ways we could have written this.
  23. Another approach would be to start with "i" equals zero,
  24. make the test condition "i" is less than "n".
  25. So now we're stopping as soon as "i" is equal to "n".
  26. For this to print out the correct numbers, though, now we need to move the print.
  27. We want the print to be after we added 1 to "i",
  28. so the first number we print is supposed to be a 1, which will be the case here.
  29. And the final number we print should be "n", which is the case here.
  30. Once the value of "i" is "n", this test will be False
  31. and we don't go through the loop anymore--so
  32. when we run this, we get the same result, printing 1, 2, 3.
  33. So as another test, let's see what happens when we pass in zero.
  34. And when we run this, it doesn't print anything.
  35. That's because when "i" is zero, "i" less than "n" evaluates to False.
  36. Zero is not less than zero, so we don't go through the loop at all
  37. and don't print anything--which seems like a pretty sensible thing.
  38. Since we said print the numbers between 1 and the target number,
  39. if the target number is zero, not printing anything sort of makes sense.