--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.
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.
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 Continue reading "EASY AS 1,2,3?"