About 'for' loop in Python
In Python, the 'for' loop is used to iterate over a sequence or any iterable object such as a list, tuple, string, or range.
You can iterate over the numbers of a range() function using 'for' loop.
About range() function in Python
In Python, the range() function is used to generate lists containing arithmetic progressions (sequence of numbers) on the fly.
It's commonly used in 'for' loops to iterate over a sequence of numbers.
Iterating over range() elements using 'for' loop in Python
1. Create a for loop with range() function (for number in range(1, 10):
) where 'for' starts the loop, 'number' is a variable that represents an element of the range(1, 10), 'range(1, 10)' is a range function whose starting value is 1 and stopping value is 10 (not included), and the colon (:) is part of the syntax.
Please note that stopping value '10' is not included in the sequence of numbers.
2. Now create a block of code that will be executed during each iteration of the for loop. The print message print(number)
is the block of code to be executed. It will print each number of the range.
Please take a closer look at the following example:
Example of for loop using range
Output of the above example
1 2 3 4 5 6 7 8 9