Until now, you've only used the for loop to execute an action for each element in a collection. However, sometimes you might want to run the loop a certain amount of times. For this, you could use the range() function:
for i in range(5):
print(i)
What Does the Python Range Do
The code in the body of this for loop will run exactly five times. In the example above, you're printing the iterator i during each loop. What do you think that i will be for the different iterations?
Info: Behind the scenes of range(), you're still doing the same thing as before with strings. You're executing the action for each element in a collection. range() creates something similar to a collection of numbers, starting from 0 to the number you pass as an argument to the function minus one.
Using range() with a for loop allows you to specify the number of times you want the code in a for loop to run.
A Sequence Of Numbers
The range() function allows you to do more than just iterate a certain amount of times. As mentioned in the note further up, it creates an immutable sequence of numbers, which is similar to the immutable sequence of characters you got to know as strings.
Add Operations in the Loop
Just like you can work with each individual character while looping over a string, you can also perform an operation on each number while iterating over a range:
for n in range(100):
if n % 2 == 0:
print(n)
The code snippet above creates a range of 100 items, from 0 to 99, and iterates over each of these numbers. Then you added a conditional statement that checks whether each number is divisible by 2 without leaving any remainder. Finally, it prints those numbers.
This means that the code snippet will print out all even numbers between 0 and 99.
Tasks
- Read up on the documentation of
range(). - How can you include the number
100in your calculation? - How can you start at a different number than
0? - What can you do with the
stepargument? - Step through the execution of a
loop on a range using the Python Visualizer.for
You'll frequently see range() used in combination with Python for loops, because it represents a quick way of creating sequences of numbers as well as deciding how often your loop should execute.
In the next lesson, you'll literally go deeper by exploring how you can create nested for loops.
Additional Resources
- Python Documentation: Ranges
Summary: Python Range Function
range()creates an immutable collection of numbers- Ranges are convenient when running a loop for a specific number of times
- The numbers created in the range can be used inside the loop to run operations