Python’s Range() function is a perfect example of why Python is one of the world’s most popular programming languages. It offers a variety of built-in tools that aid in the development of any program, and today we’ll be reviewing one of these functions, but don’t worry! We’ll make it simple and provide examples for you.
The Range() function is a useful statement when we have to repeat a command a fixed number of times. Within that context, we’ll teach you how the Range() function syntax works, and then we will go over a few examples.
Don’t feel intimidated! This is a basic resource that you’ll understand in no time.
Let’s start coding!
Python’s Range() Explained
The Range() function is a Python native function primarily used for creating a sequence of numbers, generally starting at 0 and increasing by 1 each time.
Range() stops at a specified number, and we can change any of the parameters of the function. That’s the quick explanation. But from now on, we need to understand that Range() is, in fact, a loop, just like a “For” loop or “While” loop.
In this article, all of our examples are based on Python 3 syntax. The Range() function can be found in versions 2 and 3 of Python, and each one works very differently. Actually, Range() is an improved version of the xrange() function of Python 2, but we won’t get into that.
Not making this distinction could lead to some confusion, but you just need to remember that Range() is a Python 3 function. Having said that, the best way to learn any programming concept is to try it out for ourselves. So, why don’t we jump to some code examples?
Before we jump into some examples, here is a quick video that explains what a Range() function is in general:
Python’s Range() Function Syntax
As we mentioned before, the Range() function allows us to generate a sequence of numbers. To control the output, we have a series of parameters that let us specify the sequence’s range and how the number’s count behaves.
These parameters are called Start (optional, establishes the first number of the sequence), Stop (the value at which the loop ends), and Step (the difference between any two digits).
The Range function will work with one, two, or three parameters. If we only specify the stop parameter, it will start at 0 by default and increase by 1.
The number specified as “stop” will not be included in the final sequence. This is important to remember, so check out this piece of code with the basic syntax and see if you can spot all of these elements:
for i in range(10): print(i)
We can see a list of numbers in the output. This list starts at 0 and finishes at 9. The number specified at “stop” is not included.
Let’s see an example with two parameters:
for i in range(1, 10): print(i)
Adding another parameter takes Python’s Range() function to a whole other level. The default is always 0, but now we have control over where the sequence starts.
The last printed number is still one less than the one specified as the “stop” parameter. Be aware that this will always be the case with all Range() function statements.
Let’s add the final parameter, step:
for i in range(1, 10, 2): print(i)
Range() is now taking in all three parameters available to us developers. The real deal starts when you let Range() know how the step variable should behave, as this opens a whole spectrum of possibilities. Just wait and see!
The example above shows how to return an arithmetical resolution with the string as an extra ingredient. The first number gradually increments until we reach the stop value.
We’ll get into more complex examples later, but first, let’s talk about another interesting quirk of this function. The Range() function let us decrement the values as we step through the sequence. Sounds fancy, but let’s see how it actually works.
Backwards Range() Function
Until now, all of our examples use a positive number with the step parameter.
What happens if we specify a negative value instead?
for i in range(10, -11, -5): print(i)
In the example above, we specified -5 as the step value. This decrements the sequence until we get to -10. We can get the same results with a For loop, but now with Range(), we have a cleaner and simpler syntax. The idea is that by just looking at the parameters, we easily know how the sequencing will behave.
But wait, there is even a simpler way to write the same function we saw above. Python includes a built-in reverse() function. Combining this function with Range() will get the results we want! Let’s see how:
for i in reversed(range(10)): print(i)
Range() and Float Numbers
So far, we’ve only defined the function parameters using whole numbers, and because of that, we’ve missed a certain quirk that Python’s Range() function has.
Put simply, Range() cannot run with float numbers. Read that again: Range() doesn’t work with float numbers, and don’t even try reverse(range()) with a float number.
Float numbers are any number that includes a decimal point. If you try to build Range() using a float, you will get an error like this:
for i in range(5.1): print(i)
Now, there is a way to make this work if you need it to. Luckily, we can troubleshoot this situation using Python’s NumPy third-party library. To install it on your computer, just type the following code:
Next, you write the import keywords, and NumPy is ready to run. Operating Range() with float numbers and NumPy will look like this:
import numpy as np for i in np.range(0.5, 2.1, 0.5): print(i)
That’s it, you have the Range() function with the additional call to NumPy. Please keep in mind that the computation of decimals sometimes returns unexpected and confusing results that lead to hours and hours of debugging when it truly should be a simple computation.
Anyways, you don’t have to worry too much about this if you make sure to import NumPy correctly. However, there are a few common mistakes coders make that you might want to know about.
Common Range() Function Mistakes to Avoid
We have taken a look at how Range() parameters work in previous sections of this article. Now, one thing we didn’t mention before is a common error that you’ll make sooner or later if you start playing around with this resource.
Let’s remember the syntax of this function’s parameters:
range(start, stop, step)
The start and step parameters are optional, but the stop parameter must always be defined as a number that your sequence could plausibly stop at. For example, defining it as zero in some way (either by mistake or intentionally) if your sequence is wholly comprised of positive numbers will cause your whole code to come crashing down.
Now, let’s look at this example of another common mistake:
for i in range(2, 12, 0) print(i)
We can’t define the step parameter as zero. This will make your code crash because, technically, the sequence can’t move forward. You’re telling your code to walk zero steps from one number to the other, so naturally, this function doesn’t know what to do.
You just need to remember that the default step is 1, so if you want this value there is no need to specify it in the function.
Conclusion: How To Use Python’s Range() Function, With Examples
Now that we reached the end of the article, it’s fair to say that you have mastered Range() functions, so congratulations!
Now you have tools to create a sequence of numbers, and like any other loop, the Range() function is essential in many applications.
We have learned how to write Range()’s simple syntax, putting to work all three parameters that define the sequence. To further add to this, we now know how to avoid the main mistakes a new coder might make.
Now, it’s time to try the Python Range() function in your programs and projects. Also, if you want to know more about Range(), you should check out Python’s official documentation.
The image featured at the top of this post is ©Mongta Studio/Shutterstock.com.