Understanding Python range() and Loop Control Statements
This article explains how Python's range() function generates numeric sequences with various start, stop, and step parameters, demonstrates converting ranges to lists, and describes loop control statements like break, continue, pass, and the else clause within for/while loops.
Python's built‑in range() function is used to generate arithmetic sequences for iteration. For example, range(1,5) produces numbers 1 to 4, while range(1,5,2) yields 1 and 3, and range(5,-1,-1) counts down from 5 to 0.
Typical usage converts the range to a list:
>> list(range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> list(range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >> list(range(0,40,5)
[0, 5, 10, 15, 20, 25, 30, 35]When iterating with for , the range can drive the loop:
>> for i in range(2,11):
... print(i)
2
3
4
5
6
7
8
9
10Python also supports loop‑control statements borrowed from C:
break : exits the nearest for or while loop.
continue : skips the rest of the current iteration and proceeds to the next.
pass : a null operation used when a syntactic statement is required but no action is needed.
An else clause can follow a loop and runs only if the loop completes without encountering a break :
>> for i in range(5):
... if(i == 4):
... break;
... else:
... print(i)
... else:
... print('for statement is over')
0
1
2
3The article also includes illustrative images (omitted here) and links to related Python tutorials.
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.