3.1.2.5 Loops in Python | for

More about the for loop and the range()function with three arguments

The range() function may also accept three arguments - take a look at the code in the editor.
The third argument is an increment - it's a value added to control the variable at every loop turn (as you may suspect, the default value of the increment is 1).
Can you tell us how many lines will appear in the console and what values they will contain?
Run the program to find out if you were right.

You should be able to see the following lines in the console window:
The value of i is currently 2 The value of i is currently 5
Do you know why? The first argument passed to the range() function tells us what the starting number of the sequence is (hence 2 in the output). The second argument tells the function where to stop the sequence (the function generates numbers up to the number indicated by the second argument, but does not include it). Finally, the third argument indicates the step, which actually means the difference between each number in the sequence of numbers generated by the function.
2 (starting number) → 5 (2 increment by 3 equals 5 - the number is within the range from 2 to 8) → 8 (5 increment by 3 equals 8 - the number is not within the range from 2 to 8, because the stop parameter is not included in the sequence of numbers generated by the function.)

Note: if the set generated by the range() function is empty, the loop won't execute its body at all.
Just like here - there will be no output:
for i in range(1, 1): print("The value of i is currently", i)

Note: the set generated by the range() has to be sorted in ascending order. There's no way to force the range() to create a set in a different form. This means that the range()'s second argument must be greater than the first.
Thus, there will be no output here, either:
for i in range(2, 1): print("The value of i is currently", i)

Let's have a look at a short program whose task is to write some of the first powers of two:
pow = 1 for exp in range(16): print("2 to the power of", exp, "is", pow) pow *= 2
The exp variable is used as a control variable for the loop, and indicates the current value of the exponent. The exponentiation itself is replaced by multiplying by two. Since 20 is equal to 1, then 2 × 1 is equal to 21, 2 × 21 is equal to 22, and so on. What is the greatest exponent for which our program still prints the result?
Run the code and check if the output matches your expectations.


for i in range(2, 8, 3):
print("The value of i is currently", i)
  • Console 

Comments

Popular Posts