In Python, a range is typically created using the built-in range() function, which generates a sequence of numbers that includes the start value but excludes the end value.
An inclusive range refers to a sequence of numbers where both the start and end values are included in the sequence. That means we need to use range(start, end + 1). The full syntax is below:
range(start, end + 1, step)
The above figure represents a range that includes both start and end values. Let’s implement it in a program.
# Start value of the range start = 5 # End value of the range end = 10 # The end value is increased by 1 to include the end value in the range for i in range(start, end + 1): print(i) # Output: # 5 # 6 # 7 # 8 # 9 # 10
Passing a “step” parameter
The step argument specifies the increment (or decrement) between each number in the sequence. It describes how the numbers progress in the sequence.
By default, the value of a step is 1, but you can set it to any value you prefer.
# Start value of the range start = 5 # End value of the range end = 11 # Loop over a range from 'start' to 'end' (inclusive) with a step of 2 for i in range(start, end + 1, 2): print(i) # Output: # 5 # 7 # 9 # 11
When you are using “step” and you want to include the exact end value, make sure that it’s reachable based on the step: In the above code, I used start = 5, end = 11, and step = 2, and we got 5, 7, 9, and 11.
Inclusive range with negative numbers
You can print the numbers, including the “end” point from negative to positive, using the range() function.
for i in range(-2, 2 + 1): print(i, end='\n') # Output: # -2 # -1 # 0 # 1 # 2
That’s all!