Greetings, Explorer! In today's adventure, we're traversing the vast expanse of range() and enumerate(). These two functions will serve as your co-pilots, guiding your spaceship, the for loop, through the expansive universe of Python. We're set to delve into each function, uncovering hands-on examples and real-life applications.
Our first destination is the planet range(). This Python function generates a sequence of numbers, which are pivotal when directing a loop a specified number of times.
The range() function can accept three different sets of parameters:
range(stop): generates numbers from0tostop - 1.range(start, stop): generates numbers fromstarttostop - 1.range(start, stop, step): generates numbers fromstarttostop - 1in steps ofstep.
The start parameter specifies the starting point of the sequence, stop marks the endpoint (which isn't included in the sequence), and step is the increment amount for the sequence. By default, start is 0, and step is 1.
Let's see it in action with a simple for loop.
Output:
The range(5) command generates numbers from 0 to 4.
Now, let's experiment with a different value for start and a step:
Output:
As you can see, the above code starts at 1 and goes up to 9, but it only prints every second number due to the step of 2.
Our next stop is galaxy enumerate(). This function serves as our real-time radar when voyaging through a list, as it provides both the index and value of each item. Here's how:
Output:
It gives both the index (index) and corresponding checkpoint (check_point) in the journey.
