Definite iteration is iteration a fixed number of times, usually looping through some kind of iterable like a list.
Python implements definite iteration using for loops. It consists of three parts:
Initialization: A variable is declared and initialized with an initial value.
Condition: A condition is checked before each iteration. If the condition is true, the loop continues; otherwise, it terminates.
Update: The variable is updated after each iteration.
Here's an example of a for loop:
for i in range(5): print("i is currently ", i)
The loop repeats 5 times, each time incrementing i by one - 0,1,2,3,4
Each time through the loop it checks to see if there is still a number left in the range. if there are no numbers remaining in the range the loop terminates
What is the purpose of a for loop?
Which keyword is used to define a for loop?
How many parts does a for loop declaration consist of?
Range() function
Definition:
The range() function in Python is used to generate a sequence of numbers. It returns a range object which represents a sequence of numbers within a specified range. The range object can be used in for loops or converted to other iterable data types like lists.
Syntax:
range(start, stop, step)
start: Optional. The number to start the sequence from. If not provided, it defaults to 0.
stop: Required. The number to stop the sequence at (exclusive). It does not include this number in the sequence.
step: Optional. The difference between each number in the sequence. If not provided, it defaults to 1.
Example:
code:
for i in range(0, 10, 2):
print(i)
output:
0
2
4
6
8
Explanation:
In the above example, the range function is used to generate a sequence of numbers from 0 to 10 (exclusive) with a step size of 2. Each number in the sequence is printed using a for loop.