range ¶
First, let's just write code that will print something five times.
This is the perfect task for the
range
function in Python.
range
simply generates numbers from a starting point up to, but not including, the stopping point.
You call it by providing
range(start, stop, step=1)
; thus, we should use
range(0, 5)
.
print([range(0, 5)])
[range(0, 5)]
Wait a second, that does not look right.
I should have a list of numbers like this:
[0, 1, 2, 3, 4]
.
This looks nothing like it.
Normally we define a list with
[]
, but this does not seem to work.
It turns out,
range
is a special type of function called a
generator
.
These functions do not
return
one value, but they repeatedly
yield
one value at a time.
For example, imagine you are building an Ikea table and have a friend to help you.
Your friend is responsible for handing you the screws and you screw them in.
If you asked your friend to
return
the screws, they would hand you all of the screws at once.
If you asked your friend to
yield
the screws, they would hand you one screw at a time each time you asked.
When we use
[range(0, 5)]
, Python just takes the
range(0, 5)
function and puts it into a list.
It does not ask
range
to give it numbers.
In actuality, we need to use
list()
instead.
This function still creates a list, but it is designed to ask whatever is in between
()
to keep handing it values until it runs out.
Also, we can leave out the
0
in our
range
call, as this is the default value.
print(list(range(5)))
[0, 1, 2, 3, 4]
That looks better!
Now, let's just have Python print each number.
We do this with a
for
loop.