For loops repeat a block of code for all of the values in a list, array, string, or range().We can use a range() to simplify writing a for loop. 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().
Loops and range function in python
python range() function
The python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequence on a sequence of numbers using python loops.
for i in range(5) : print(i, end=" ") print() output: 0 1 2 3 4
What is the use of the range function in python
In simple terms, range() allow the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end, as well as how big the difference will be between one number and the next. python range() function takes canĀ be initialized in 3 ways.
- range (stop) takes one argument.
- range (start, stop) takes two arguments.
- range (start, stop, step) takes three arguments.
Example of python range (stop)
In this example, we are printing the number from 0 to 5. we are using the range function in which we are passing the stopping of the loop.
# printing first 6 # whole number for i in range(6) : print(i, end=" ") print() output: 0 1 2 3 4 5
python range (start, stop)
In this example, we are printing the number from 5 to 19. we are using the range function in which we are passing the starting and stopping points of the loop.
# printing a natural # number from 5 to 20 for i in range(5, 20): print(i, end=" ") output: 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
python range (start, stop, step)
In this example, we are printing the number from 0 to 9 with the jump of 2. we are using the range function in which we are passing the starting and stopping points with the jump of the iterator.
for i in range(0,10,2): print(i, end=" ") print() output 0 2 4 6 8