English

range() function in python does not include the stop value. Write a generator function equivalent to range() function that includes the stop value also.

Advertisements
Advertisements

Question

range() function in python does not include the stop value. Write a generator function equivalent to range() function that includes the stop value also. The function will take three arguments start, stop and step and will generate the desired list.

Code Writing
Advertisements

Solution

The generator must support both increasing and decreasing sequences and must reject a zero step.

def inclusive_range(start, stop, step=1):
    if step == 0:
        raise ValueError("step cannot be zero")

    if step > 0:
        while start <= stop:
            yield start
            start += step
    else:
        while start >= stop:
            yield start
            start += step

Example:

print(list(inclusive_range(1, 5, 2)))
print(list(inclusive_range(5, 1, -2)))

Output:

[1, 3, 5]
[5, 3, 1]
shaalaa.com
  Is there an error in this question or solution?
Chapter 8: Exception Handling & Generate Functions - EXERCISE [Page 158]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 8 Exception Handling & Generate Functions
EXERCISE | Q 12. | Page 158
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×