14. Passing a range into a function


#1

Hi,

I'm having trouble understanding how the
range()
function works. Could someone please explain it to me?

Thanks.


#2

range is a built in function (documentation) which can have up to 3 arguments:

range(start, stop, step)

for this exercise you need start and stop (steps are 1 by default). for example:

range(0,10)

will give you: 0,1,2,3,4,5,6,7,8,9 (10 is not included, it is less then 10)

You need to pass range into the function so the range function gives you: 0,1,2


#3

Okay, so if I wanted the numbers in the middle (4,5,6), how would I go about it? Also, if I just wanted one random number e.g. 9, how would I go about that?


#4

if you just want one number, i wouldn't even bother using range

what do you think the start and stop values should be for range? (i even included a link to documentation in my first answer, which you can check)


#5

I still don't understand it fully. What exactly do the start, stop and step values refer to? How do we decide which values to assign to start, stop and step? Is there a more detailed document you could link me to since the one you provided is a bit brief?


#6

the numbers you want as output? start for example could be 2, stop could be 5, and step 1, which will be:

range(2,5,1)

which produce the following output:
2,3,4

But range should already be covered, you can revisit that exercise? How can you not understand that start, stop and step represent numbers? Even with the documentation i linked to


#7

I understand that start, stop and step represent numbers. What I don't understand is the following:

  1. How do you know which numbers to assign to start, stop and step? Do you just choose any random number you want or is there some science behind it?

  2. How does range(2,5,1) produce 2,3,4? How does 2 (start) produce an output of 2, how does 5 (stop) produce an output of 3 and how does 1 (step) produce an output of 4?

I have revisited the exercise, but I'm still a bit confused. :confused:


#8

you use the range function, you can pass it the numbers you need. In case of the exercise: range(0,3) given you want 0,1,2 as output. (steps are +1 by default)

No no no no, you don't get it. Range starts at 2, then it increases with steps of one until it reaches 5, which produces the following output: 2,3,4

lets look at some js code to make more sense of it:

for (i = 2; i < 5; i = i + 1){
  console.log(i);
}

console.log is what we use instead of print. So range is basically a function someone build, so you don't have to write a for loop


#9

Does that mean range doesn't go beyond 5?


#10

5 is even not included, given i use < (lesser then) and not <= (equal or less then)


#11

Oh, okay. Thanks for your help. :thumbsup: