Counting loop
Completion requirements
In e.g. C/C++, C# and Java a loop controlled by a counter is implemented without problems:
Example:
for(int i = 0; i <= 3 ; i++) // for(<initialization>;<condition>;<increment>
{
System.out.println(i + ". Item"); // Java syntax
}
Output:
0. Item
1. Item
2. Item
3. Item
In contrary in Python the For loop iterates over a list:
for i in list: # Python syntax
...
A special counting list does not exist in Python!
Therefore for this purpose at first a list with numbers has to be created:
list = [0,1,2,3]
for i in list:
print(str(i) + ". Item")
The output will be the same as shown above:
0. Item
1. Item
2. Item
3. Item
Function range()
To simplify the creation of the required list, the range() function is used.
list = range(4)
for i in list:
print(str(i) + ". Item")
or directly
for i in range(4):
print(str(i) + ". Item")
Further use of range()
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The number passed as a parameter is never part of the list; it represents the length of the list starting with 0.
The list can also begin with a number other than 0. The function then receives the start value as the first parameter and the end value as the second parameter.
>>> range(5, 10)
[5, 6, 7, 8, 9]
The step length can also be passed as a third parameter:
>>> range(0, 10, 3)
[0, 3, 6, 9]
Negative information is also possible:
>>> range(-10, -100, -30)
[-10, -40, -70]
Last modified: Tuesday, 29 October 2019, 1:53 PM