In this lesson, we will focus on iterating over sequences of numbers using the range() function.
The range() function
The range() function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and ends at a specified number. For example:
range(5) # returns the sequence [0, 1, 2, 3, 4]
Notice that the argument is an exclusive upper bound. The function stops when hitting that value, without appending it to the sequence. That's why range(5) is not the values of 0 to 5, but the values 0 to 4.
Looping over a range:
Now, we can use a for loop along with the in keyword to iterate over a range, like this:
for i in range(4):
print("For loops are cool!")
The output of this code is:
For loops are cool!
For loops are cool!
For loops are cool!
For loops are cool!
Assignment
Let's print "I promise to learn coding." 5 times using a for loop.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
