EASY AS 1,2,3?

--Originally published at Coding The Future

Image by Austris Augustus

Greetings everyone! And welcome to my last mastery article. To be honest, I thought I was done, but I just noticed I was missing an important concept in Python: ranges.

Ranges in Python are quite peculiar, because they work a little differently from other languages and also a little differently from what we're used to in Math class. Let's get right into it.

Declaring Ranges

Ranges can be used when we need to work with a set number of elements, like running a loop for a determined range.

To declare a range, we simply call the range( ) function, like in the following example:


In this example, where only one number is included, Python asumes that your range will begin at zero, and end in 7. This range has seven elements, and it starts at zero. So if I printed a counter for the range, it would return 0,1,2,3,4,5,6.

However, things get a little tricky when we add a second number to the function, like this:


In this example, I am working with a range from 1 to 7, but in Python this means from 1 to 6. The first number indicates where the range starts, but the second number represents the number after the last number in the range. So once again, if I were to print a counter, I would get 1,2,3,4,5,6. See? The seven is not included, and even though there is mathematically seven numbers between 1 and 7, the range only has six.

Using Ranges

We can use ranges for a variety of things, but the most common use is for loops. Here's an example of a for loop that prints Hello #n 5 times:

for n in range(1,6): print("Hello #" + n)

If we run this loop, it would the following:

>>> Hello #1
>>> Hello #2
>>> Hello #3
>>> Hello #4
>>> Hello #5

Therefore, ranges will come in handy in these situations. Well, that's pretty much it for today. And pretty much it for the semester as well, haha.

I invite you to go and check out Quirino's Awesome Projects, whose blog post served as inspiration for this one.

My last post, which should be up Friday at the latest will include a course review of TC101 with Professor Ken Bouer.

See y'all soon!

comments powered by Disqus