
The stop value of the range() must be specified, but we can also modify the starting value and the step between integers in the range(). We can use a range() to simplify writing a for loop.
PYTHON FOR LOOP CODE
In this article, we looked at for loops in Python and the range() function.įor loops repeat a block of code for all of the values in a list, array, string, or range(). In our final example, we use the range of integers from -1 to 5 and set step = 2. The optional step value controls the increment between the values in the range. In our next example, we set start = -1 and again include integers less than 5. In the example below, we have a range starting at the default value of 0 and including integers less than 5. That is, for (int i0 i In the example below, we use a for loop to print every number in our array. For Loops in Pythonįor loops repeat a portion of code for a set of values.Īs discussed in Python's documentation, for loops work slightly differently than they do in languages such as JavaScript or C.Ī for loop sets the iterator variable to each value in a provided list, array, or string and repeats the code in the body of the for loop for each value of the iterator variable. In this article, we will look at a couple of examples using for loops with Python's range() function. Loops are one of the main control structures in any programming language, and Python is no different.